How to Replace Text Inside a div Element with JavaScript?
To replace text inside a div element with JavaScript, you can use the innerHTML property of the element. The example is given below.
<div id="myDiv">Old Text</div> <button onclick="changeText()">Change Text</button> <script> function changeText() { const myDiv = document.getElementById("myDiv"); myDiv.innerHTML = "New Text"; } </script>
In the above example, the changeText() function retrieves the div element with document.getElementById("myDiv"), and then sets its innerHTML property to the new text that you want to replace it with. When the user clicks the button, the changeText() function is called and the text inside the div is replaced with the new text.
Change text inside div using innerText property. #
Using the innerText property: You can replace the content of a div element by setting its innerText property to a new value.
<script> const myDiv = document.getElementById('my-div'); myDiv.innerText = 'New content'; </script>
Change text inside div Using the textContent property. #
Alternatively, you can replace the text content of a div element by using its textContent property. This will only change the text content, not any HTML markup inside the div.
<div id="myDiv">Old Text</div> <button onclick="changeText()">Change Text</button> <script> function changeText() { const myDiv = document.getElementById("myDiv"); myDiv.textContent = 'New text'; } </script>
Replace text inside div using document.createTextNode() #
You can create a new text node with the text content you want to replace the div content with, and then replace the div's child node with this new text node.
<div id="myDiv">Old Text</div> <button onclick="changeText()">Change Text</button> <script> function changeText() { const myDiv = document.getElementById("myDiv"); let newTextNode = document.createTextNode('New text'); myDiv.replaceChild(newTextNode, myDiv.childNodes[0]); } </script>
Using document.createElement() and appendChild() #
You can create a new HTML element with the text content you want to replace the div content with, and then append that element to the div.
<div id="myDiv">Old Text</div> <button onclick="changeText()">Change Text</button> <script> function changeText() { const myDiv = document.getElementById("myDiv"); let newParagraph = document.createElement('p'); newParagraph.textContent = 'New text'; myDiv.appendChild(newParagraph); } </script>
Change text inside div using jQuery's text() method. #
If you are using the jQuery library, you can use its convenient text() method to replace the text content of a div element.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <div id="myDiv">Old Text</div> <button onclick="changeText()">Change Text</button> <script> function changeText() { $('#myDiv').text('New text'); } </script>