JS Change Text in Div
In this article, we will see how to change the text of a div in JS.
Why should we change the text of a div?
- If you are building a multi-language website, you may need to change the text of a div element based on the user’s language preferences.
- You can create a more engaging and interactive experience for your users, by changing the text of a div element.
3 Ways to change the text of div
Method 1. innerHTML property
In this method, we set or get the HTML content within an element using JS innerHTML property. To change the text of a div using innerHTML, we can simply set the property to the new text you want to display:
<div id="Div1">Original Text</div>
// Get the ID of div element const myDiv = document.getElementById('Div1'); // Set the new value to div myDiv.innerHTML = 'New Text'
In this code:
- In this example above, we have created the ‘div’ tag with idName ‘Div1’. We have placed the text ‘Original Text’ inside the div tag.
We can also use the simplified method of innerHTML property. We don’t need to create variables. In this method, we can get id and set a new value of div in a single line like:
document.getElementById("Div1").innerHTML = "New text";
Since this is the easiest method, we will look at the shorthand methods in the following two methods
Method 2: innerText property
It is similar to the innerHTML property, but it considers the element’s visibility and any CSS styles that might affect the display of the text.
<div id="myDiv">Original Text</div>
document.getElementById("myDiv").innerText = "New text";
In this code:
- In this example, we’re using the ‘getElementById’ method to select the div with the ID of “myDiv”.
- Then set the innerText property to “New text”.
- This will replace any existing text content inside the div with the new text.
Method 3: textContent property
In this method, we set or get only the text content of an element, without any HTML markup. We change the text of a div using the ‘textContent’ property, you can do it like this:
document.getElementById("myDiv").textContent = "New text";
In this example, we have also selected the div IDname using the the ‘getElementById’ method and set new text using the ‘textContent’ property as above.