Categories
JavaScript Answers

How to change an element’s text without changing its child elements with JavaScript?

Spread the love

Sometimes, we want to change an element’s text without changing its child elements with JavaScript.

In this article, we’ll look at how to change an element’s text without changing its child elements with JavaScript.

How to change an element’s text without changing its child elements with JavaScript?

To change an element’s text without changing its child elements with JavaScript, we set the nodeValue property of the text node.

For instance, we write

const div = document.getElementById("foo");
div.firstChild.nodeValue = "New text";

to select the element with getElementById.

Then we get its first child node with firstChild.

And then we set its content by setting the nodeValue to a new value.

Conclusion

To change an element’s text without changing its child elements with JavaScript, we set the nodeValue property of the text node.

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 *