How to Change Button Text in Javascript
In this tutorial, you will learn how to change button text in javascript. If want to change text content dynamically of any element, then indeed javascript is the best option since javascript gives you the ability to manipulate the DOM in any manner you want.
To change the text content of any element, you can make use of innerText
or textContent
property. The innerText
property is best suited when you want to change the text that is visible to the user. The textContent
property should be used when you want to change both the visible and invisible text content of an element.
In the following example, we have a button
element and we want to change its text upon click. Please have a look over the code example and steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - The
button
element has“Send Message”
as its inner text. - The
h1
element is empty for now. We will add some text content to it using javascript. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <button>Send Message</button> <h1></h1> </div> <script src="script.js"></script> </body> </html>
div { display: flex; justify-content: center; } button { padding: 10px; }
Javascript
- We have selected the
button
element andh1
element using thedocument.querySelector()
method and stored them inbtnSend
andmessage
variables respectively. - We have attached a
click
event listener to thebutton
element. - In the event handler function, we are using the
innerText
property to change the text of thebutton
element to“Sending…”
- We are using
setTimeout()
method with a delay of 5 seconds. - After completion of 5 seconds, we will hide the
button
element by setting itsdisplay
property tonone
and add the text“Message Sent”
to theh1
element.
let btnSend = document.querySelector('button'); let message = document.querySelector('h1'); btnSend.addEventListener('click', () =>{ btnSend.innerText = 'Sending...'; setTimeout(()=>{ btnSend.style.display = "none"; message.innerText = 'Message Sent'; },5000); });