Table of Contents
JavaScript is great for creating dynamic web page, thanks to its ability to programmatically alter the DOM.
One of the most common ways to alter the DOM is by changing the text of a button element.
In this post, we'll learn how to change the text of a button element using JavaScript.
Change the text of a button element
To learn how to do this, we'll use the following HTML:
HTML<input type="button" value="Click Me!" class="button" />
The button element has a value attribute, in this case, Click Me!
.
To change the text, first we must get a reference to the button element.
We can do this by using the document.querySelector()
method.
JAVASCRIPTconst button = document.querySelector(".button");
Once we have the button, we can alter the text of the button by setting a new value for the value
attribute.
Here's how to do that:
JAVASCRIPTconst button = document.querySelector(".button");
button.value = "This is a new text!";
After that, the DOM looks like this:
HTML<input type="button" value="This is a new text!" class="button" />
While this changes the value, it does not change the text that is displayed on the button. To change the text, we must use the innerText
property.
JAVASCRIPTconst button = document.querySelector(".button");
button.innerText = "This is a new text!";
After this code is run, the user will now see a button with the text This is a new text!
.
Conclusion
In this post, we learned how we can use JavaScript, value
and innerText
to change the text of a button element.
This is useful when creating dynamic web experiences that require a changing button programmatically.
Hopefully, this post has helped you. Happy coding!
- Getting Started with Express
- Create an RSS Reader in Node
- How to deploy a Deno app using Docker
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript