Thought leadership from the most innovative tech companies, all in one place.

How to Replace Text Inside a div Element with JavaScript?

image

Sometimes, we want to replace text inside a div element with JavaScript.

In this article, we'll look at ways to replace text inside a div element with JavaScript.

Set the innerHTML Property of an Element

One way to replace the text inside a div element with JavaScript is to set the innerHTML property of an element to a different value.

If we have the following HTML:

<div>hello world</div>

Then we can write:

const div = document.querySelector("div");
div.innerHTML = "My new text!";

to select the div with querySelector .

And then we can set the innerHTML to a new string.

Set the textContent Property of an Element

Another way to replace the text inside a div element with JavaScript is to set the textContent property of an element to a different value.

If we have the following HTML:

<div>hello world</div>

Then we can write:

const div = document.querySelector('div')
div.textContent = "My new text!";

to select the div with querySelector .

And then we can set the textContent to a new string.

Then we get the same result as before.

Set the innerHTML Property of an Element to an Empty String and Insert a new Child Text Node to the Element

Another way to replace the text in a div is to set the innerHTML property to an empty string.

Then we can add a new text node and insert it into the div.

If we have the following HTML:

<div>hello world</div>

Then we can write:

const div = document.querySelector("div");
div.innerHTML = "";
div.appendChild(document.createTextNode("My new text!"));

to set innerHTML to an empty string.

Then we call document.createTextNode to create a new text node with the text in the argument.

And then we call appendChild to insert the text node to the div.

Conclusion

There are various ways we can use to replace text in a div element with new text in JavaScript.




Continue Learning