How to Change Text on HTML Pages using JavaScript
JavaScript makes it really easy to customize the front-end experience for users thanks to its built-in APIs.
One of the most common tasks is to change the text or HTML of a page.
This allows you to do things like change the text of something after a button press.
In this post, we'll learn how to change the text of a page using JavaScript.
How to Change the Text of a Page
The most straightforward way to change the text of a page is to use the textContent
property of an element.
Let's see how this works using the following HTML:
HTML<div>
<p class="text">This is the original text.</p>
</div>
First, let's query for the element we want to change:
JAVASCRIPTconst text = document.querySelector(".text");
Now, we can change the text of the element using the textContent
property:
JAVASCRIPTconst text = document.querySelector(".text");
text.textContent = "This is the new text.";
The HTML now looks like this:
HTML<div>
<p class="text">This is the new text.</p>
</div>
Let's see an interactive example of this in action:
- HTML
- JavaScript
How to Change the HTML of a Page
Keep in mind that the textContent
property only changes the text of an element.
If you want to use tags and change the HTML of an element, you can use the innerHTML
property.
Here's an example of this:
HTML<div>
<p class="text">This is the original text.</p>
</div>
JAVASCRIPTconst text = document.querySelector(".text");
text.innerHTML = "This is the <strong>new</strong> text.";
Try it for yourself:
- HTML
- JavaScript
Conclusion
In this post, we learned how to change the text and HTML of a page using JavaScript.
Simply use the textContent
property to change the text of an element.
To change the HTML of an element, you can instead use the innerHTML
property.
Thanks for reading!
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- Learn how to use v-model with a custom Vue component
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript