We can use the jQuery text() method to set the text of an HTML element.
$("#div1").text("Some text");
Let’s say I have the following HTML:
This is some text.
If we want to change the text inside the div from “This is some text.” to “This is some new text.”, we can use the jQuery text() method to do this with the following jQuery code.
$("#div1").text("This is some new text.");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1").text("This is some new text.");
If your div will contain html content, then you should use the jQuery html() method.
$("#div1").html("Some Text");
Using the jQuery text method to set the text of a div with a click
To set the text of a div on click using jQuery, we can combine the text() method with a click event.
Let’s say I have the following HTML, and I want to give the user the ability to set the text of the div below to “We just added this text using the jQuery text method!”.
Add text
We can utilize both the jQuery click() method and jQuery text() method to set the text to “We just added this text using the jQuery text method!”.
Below is the jQuery code which will allow the user to be able to update the text in the div:
$("#click-me").click(function(){
$("#div-to-update").text("We just added this text using the jQuery text method!");
});
The final code and output for this example of how to set the text of a div using the jQuery text() method is below:
Code Output:
Full Code:
Add text
Hopefully this article has been useful for you to understand the jQuery text method.