Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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