Categories
JavaScript Answers

How to Get the Text Nodes of an Element with JavaScript?

Spread the love

Sometimes, we want to get the text node of an element with JavaScript.

In this article, we’ll look at how to get the text node of an element with JavaScript.

Get the Text Nodes of an Element with JavaScript

To get the text node of an element with JavaScript, we can use the document.createNodeIterator method to iterate through all the text nodes.

For instance, if we have the following HTML:

<p>
  <br>some text<br>123
</p>

We can write:

let root = document.querySelector('p'),
  iter = document.createNodeIterator(root, NodeFilter.SHOW_TEXT),
  textnode;

while (textnode = iter.nextNode()) {
  console.log(textnode.textContent)
}

to select the p element with document.querySelector .

Then we create the iterator that returns the text nodes of the p element with document.createNodeIterator method.

We call it with the root element and NodeFilter.SHOW_TEXT specifies that it returns the text nodes.

Finally, we have the while loop that gets the text nodes from the iterator with the iter.nextNode method.

Then we see the text node values logged in the console log with the textnode.textContent property.

Conclusion

To get the text node of an element with JavaScript, we can use the document.createNodeIterator method to iterate through all the text nodes.

Leave a Reply

Your email address will not be published. Required fields are marked *