Take a look at the following HTML:
This is the text that appears when
the page is first loaded.
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.
//The new text that we want to show.
var newText = 'This text has been changed!';
//Change the text using the text method.
- 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.