This is a short tutorial on how to change the text of a DIV element using the JavaScript JQuery library. In this tutorial, we will change the text after a user has clicked on a button.
Take a look at the following HTML:
<div id="message"> This is the text that appears when the page is first loaded. </div> <button id="change_message">Change</button>
In the HTML above, we have two elements:
- Our div element, which contains a default piece of text. This element has the ID “message”.
- A button element, which has the ID “change_message”.
The goal here is to change the text in our “message” div as soon as the user clicks on the button.
To do this, we can use JQuery “text” method like so:
//If the user clicks on our #change_message button. $('#change_message').on('click', function(){ //The new text that we want to show. var newText = 'This text has been changed!'; //Change the text using the text method. $('#message').text(newText); });
In the JavaScript above, we did the following:
- We created a “click” event listener on our button. Once the button is clicked, our event handler function will be called.
- Inside our event handler function, we changed the text of our “message” div by using JQuery’s text method.
Note that the text method will not accept HTML. If you attempt to use a paragraph tag, for example, then the text method will escape your HTML and your p tag will end up being displayed in the browser. This is because the text method uses the DOM method createTextNode.