How to get text for element without children text with JavaScript?

Sometimes, we want to get text for element without children text with JavaScript.

In this article, we’ll look at how to get text for element without children text with JavaScript.

How to get text for element without children text with JavaScript?

To get text for element without children text with JavaScript, we can use the jQuery, contents method.

For instance, we write:

<div id='mydiv'>
  some text here
  <div>
    text for inner div
  </div>
</div>

to add some divs with text.

Then we write:

const texts = $('#mydiv').contents().filter((i, el) => el.nodeType === 3).text()
console.log(texts)

We select the parent div with $('#mydiv').

Then we get the contents of the div with contents.

And then we call filter to return the items with nodeType 3.

Finally, we get the text of the node with text.

As a result, texts is ' some text here'.

Conclusion

To get text for element without children text with JavaScript, we can use the jQuery, contents method.