How to get the text content of an element with JavaScript?

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

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

How to get the text element content of an element with JavaScript?

To get the text element content of an element with JavaScript, we can use the childNodes to get the child nodes.

And then we use textContent property to get the text content.

For instance, we write:

<div>
  hello world
</div>

to add a div.

Then we write:

const [node] = document.querySelector("div").childNodes
console.log(node.textContent)

to select the div with querySelector and use the childNodes property to get the child nodes of it.

Then we get the first node with destructuring and get its textContent property to get the text in the node.

Conclusion

To get the text element content of an element with JavaScript, we can use the childNodes to get the child nodes.

And then we use textContent property to get the text content.