We can use the textContent property in JavaScript to set the text of an HTML element.
document.getElementById("div1").textContent = "Some Text";
Let’s say we have the following HTML:
If we want to add some text to the div, #div1, we can use the textContent property to do this with the following JavaScript code.
document.getElementById("div1").textContent = "This is new text we will add to #div1";
This would update the HTML to look like this:
This is new text we will add to #div1
We can also use the textContent property to change text already in an HTML div.
Let’s say we have the following HTML:
Today is November 3rd.
If we want to change the text inside the div from “Today is November 3rd.” to “Today is December 3rd.”, we can again use the textContent property to do this with the following JavaScript code.
document.getElementById("div1").textContent = "Today is December 3rd.";
Let’s take a look at the textContent property in action with an example below.
Using the textContent property in JavaScript to set the text of a Paragraph
In this example, we will have an empty paragraph. We will let the user input any text they would like. We will then update the empty paragraph with this text using the textContent property.
Here is our simple HTML setup:
Set/Update text
We will get the user input using the value property.
We can then utilize both the onclick event and the textContent property to set and change the text of paragraph with id #div-to-be-updated with the user input. The user can change the text as many times as they want.
Below is the JavaScript code which will allow the user to be able to set/update the text in the paragraph:
function setText() {
//Get the user input
var userInput = document.getElementById("userInput").value;
//Set the text of the paragraph to be what the user entered
document.getElementById("div-to-be-updated").textContent = userInput;
};
The final code and output for this example of how to set the text of a paragraph using the textContent property in JavaScript is below:
Code Output:
Full Code:
Set/Update text
Hopefully this article has been useful for you to understand how to use the textContent property in JavaScript.