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, and h1). The div 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 the head element.
  • We have also included our javascript file script.js with a script 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 and h1 element using the document.querySelector() method and stored them in btnSend and message variables respectively.
  • We have attached a click event listener to the button element.
  • In the event handler function, we are using the innerText property to change the text of the button 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 its display property to none and add the text “Message Sent” to the h1 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);
});