Change Text with JavaScript Summary
JavaScript can replace the text inside an HTML element after the page loads. This lets a webpage update messages, labels, instructions, and other words without loading a new page.
Changing text is one of the simplest ways to see what JavaScript does. The HTML creates the original text, and JavaScript finds that HTML element and gives it new text.
How to Change Text with JavaScript
First, the HTML needs an element for JavaScript to find. This paragraph has an ID attribute named message.
<p id="message">The original text.</p>
JavaScript can then replace the words inside that paragraph with one line:
document.querySelector('#message').textContent = 'The text has changed!';
When this code runs, the browser displays The text has changed! instead of The original text.
Find the HTML Element
The first part of the line tells JavaScript what to change:
document.querySelector('#message')
document means the current webpage. querySelector() searches that page for an HTML element. The text inside the parentheses is a selector that identifies the element.
The #message selector finds the element with id="message". The number sign means it is looking for an ID, just as it would in CSS.
Replace the Text
The second part tells JavaScript what new text to use:
.textContent = 'The text has changed!';
textContent represents the text inside the selected element. The equals sign gives it a new value, and the new words go inside quotation marks.
Use textContent when you want to add or replace plain text. If the new value contains HTML tags, the browser displays them as text instead of turning them into HTML elements.
When Websites Change Text
Websites change text to show people that something happened. JavaScript might update a status message, display a form response, change a button label, or show a number that has increased.
- Change “Loading” to “Complete.”
- Show a message after someone submits a form.
- Update a total when someone makes a selection.
- Replace instructions after someone completes a step.
The example on this page runs immediately. In later lessons, you will learn how to make the same kind of change after someone clicks a button or changes an input.
Try Changing the Message
In the sandbox, change only the words inside the final quotation marks. You can write any short message you want, then select Update Code to see the new text.
You can also change the original HTML text and compare it with the text JavaScript displays. This makes it easier to see that JavaScript is replacing content that already exists on the page.