In this blog post, we will learn how to replace HTML text using JavaScript. This can be helpful when you need to
update or change the content of a webpage dynamically, without reloading the page.
innerHTML Property
The easiest way to replace HTML text with JavaScript is by using the innerHTML property. This
property can be used to get or set the HTML content of an element. Let’s see an example:
<div id="myDiv">Hello, World!</div>
<button onclick="changeText()">Click me to change text</button>
<script>
function changeText() {
document.getElementById("myDiv").innerHTML = "Hello, JavaScript!";
}
</script>
In this example, we have a <div> element with an ID of myDiv and a button with an
onclick attribute. When the button is clicked, the changeText() function is
called, which uses the innerHTML property to change the text inside the <div> element.
textContent Property
Another way to replace HTML text with JavaScript is by using the textContent property. This
property can be used to get or set the text content of an element, without any HTML tags. Let’s see an example:
<div id="myDiv">Hello, World!</div>
<button onclick="changeText()">Click me to change text</button>
<script>
function changeText() {
document.getElementById("myDiv").textContent = "Hello, JavaScript!";
}
</script>
In this example, we use the textContent property instead of innerHTML.
The result is the same as the previous example.
Conclusion
In this blog post, we learned how to replace HTML text using JavaScript by leveraging the
innerHTML and textContent properties. Both properties allow you to easily
update or change the content of a webpage dynamically.