In this post we'll look at ways to get an element's text whilst excluding text from all (or certain) child elements. We'll be considering the following HTML elements for this tutorial:
<h1 id="mainHeading"> Hello World!<span> (Ignore Me)</span><span class="date"> @ 04:45 pm</span> </h1> <h1>Lorem Ipsum</h1>
Remember to remove leading and trailing spaces from your resulting strings.
Using JavaScript node
Value Property
// using only JavaScript document.getElementById('mainHeading').childNodes[0].nodeValue; // using jQuery to select element $('#mainHeading')[0].childNodes[0].nodeValue; // output: Hello World!
In a Nutshell:
- This is the fastest method.
- Be aware! The one-line code is only good for a single matched element.
- Returns
undefined
if element is empty (i.e. it contains no text, spaces, or children). If this could be a case, a simple check for(...)childNodes.length > 0
when findingnodeValue
should do, for example:
const cNodes = document.getElementById('mainHeading').childNodes; if (cNodes.length > 0) { console.log(cNodes[0].nodeValue); }
If applying this method to get text from multiple elements, the code would look something like this:
const headings = document.getElementsByTagName('h1'); for (let i = 0; i < headings.length; i++) { for (let j = 0, heading = headings[i]; j < heading.childNodes.length; j++) { const currChild = heading.childNodes[j]; if (currChild.length) { console.log(currChild.nodeValue); } } } /* Output: Hello World! Lorem Ipsum */
The two for-loops introduce a linear complexity O(n)
, with that the result may be slower as number of items increase.
Using jQuery's contents()
Method
$($('h1').contents()[0]).text(); $($('h1').contents().get(0)).text(); // output: Hello World!
In a Nutshell:
- A short one-liner that gets the job done for a single matched element.
- If first element is empty, since we're using
contents()
, next element in the resulting matches' text is shown. If you wish to avoid this behavior, use a more specific selector such as$('#mainHeading')
to specify exactly which element to look for. - In case all elements are empty, an empty string is returned.
If you need to use this method to get text from multiple elements, the code would look something like this:
$('h1').contents().each(function() { if (this.nodeType == 3) { // you could also simply do: $(this).text() console.log(this.textContent || this.innerText || ''); } }); /* Output: Hello World! Lorem Ipsum */
Combining jQuery's contents()
Method With the not()
Method
$('h1').contents().not($('h1').children()).text(); /* Output: Hello World! Lorem Ipsum */
$('h1').contents().not($('h1').children(':not(.date)')).text(); /* Output: Hello World! @ 04:45 pm Lorem Ipsum */
In a Nutshell:
- Shortest and possibly the simplest way of getting text without children's text from multiple elements (as well as for a single element — although it won't be as efficient for single elements as it is for multiple).
- Also introduces the possibility to include text from certain child elements whilst excluding from all others.
- In case all elements are empty, an empty string is returned.
Using jQuery to Remove Children From Cloned Element
$('h1').clone().children().remove().end().text(); /* Output: Hello World! Lorem Ipsum */
$('h1').clone().children(':not(.date)').remove().end().text(); /* Output: Hello World! @ 04:45 pm Lorem Ipsum */
In a Nutshell:
- This is another method of getting text without children's text from multiple elements (as well as for a single element).
- Also introduces the possibility to include text from certain child elements whilst excluding from all others.
- In case all elements are empty, an empty string is returned.
This method is slower than the previous one because of the number of method calls and work performed by each method.
Removing Leading & Trailing Spaces
The resulting string from methods listed in this article could leave unwanted leading and/or trailing spaces. To Remove the whitespace characters (space, tab, no-break space, etc.) we could do the following:
Using jQuery's $.trim()
Method:
// jQuery 1+ $.trim(string);
Using JavaScript Native trim()
Function:
// JavaScript 1.8.1+ string.trim();
Polyfill:
Adding the following code (via MDN) before calling the trim()
function in JavaScript would add support for browsers that do not support it by default.
if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; }
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.