In this article, we are going to change the text of a button whenever it is clicked. I can't explain how easy it is! To change a button's text, we need to add a onclick event attribute to the button because whenever someone clicks the button we call a function.

JavaScript change button text onclick
Try it Yourself »
  1. First, I have created a button element with onclick event attribute and I have passed a event object.
  2. I have created the function named myFunc().
  3. Inside this function, I have change the button's value using innerText property.

If you are thinking to use innerHTML property, then you can also use that. Basically, innerHTML property is used to change or add some html inside a particular element.

Change value using innerHTML property
  function myFunc(e){
   e.innerHTML="<p style='color:#ff00ff'>Button Clicked</p>";
    
 }
Try it Yourself »

How to toggle text of s button.

Now you will learn how to toggle the value of a button using if-else statement. We can also use a switch statement instead of an if-else statement . But in this case, I will use if-else statement.

Toggle button's text using if-else statement
  function myFunc(e){
    if ( e.innerText == "click button" ){
      e.innerText = "button clicked";
    }else{
      e.innerText = "click button";
    }
  }
Try it Yourself »

I want to show you one more easy example using toggle() method.

Change button's content using toggle() method
document.querySelector('.btn').addEventListener('click', function(e) {
    e.target.classList.toggle('new-class');
    
 });
Try it Yourself »

I hope you have learned how to change a button's text in this article. But what happens if there are a lot of buttons. Do you add click event to each button manually? You can write your answer in below comment section.