One of the most common ways to alter the DOM is by changing the text of a button element.
Change the text of a button element
To learn how to do this, we'll use the following HTML:
<input type="button" value="Click Me!" class="button" />
The button element has a value attribute, in this case,
To change the text, first we must get a reference to the button element.
We can do this by using the
const button = document.querySelector(".button");
Once we have the button, we can alter the text of the button by setting a new value for the
Here's how to do that:
const button = document.querySelector(".button"); button.value = "This is a new text!";
After that, the DOM looks like this:
<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
const 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!.
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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!