CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

Change Button Text JavaScript: Perfect It in Just 3 Easy Steps!

Shawpnendu Bikash Maloroy

August 9, 2024
Change Button Text JavaScript Perfect It in Just 3 Easy Steps!
Spread the love

With JavaScript, we can change the text of any HTML element, including buttons, in real time. We can use the button onclick event to change the text. JS provides three different properties to set or get the text of an HTML element’s text. These are innerText, innerHTML, and textContent.

Table of Contents

  • HTML Button General Syntax
  • Basic Example of Changing Button Text in JavaScript
    • Change button text JavaScript – Using innerText
      • Output
    • Using innerHTML
      • Output
    • Using textContent
  • Look at the below example to understand the differences clearly
    • Output
    • Code Explanation
  • Step-by-Step Guide to Change Button Text in JavaScript
  • Methods to Select Button
    • By ID:
    • By Class:
    • By Tag:
  • Add Event Listeners
  • Frequent Use Cases
    • Form Submission:
    • Toggle Button State:
    • Loading State:
  • Tips to Improve User Experience
  • In case of Errors
  • Conclusion

In this post, “Change button text JavaScript”, we are going to explain all three-button types and all three JS properties to manipulate the HTML button’s text.

HTML Button General Syntax

<button id=”myButton” type="button|submit|reset">
Type Attribute ValueDescription
ButtonRepresents a clickable or interactive button supported by almost all modern browsers.
SubmitRepresents a submit button to submit form data to server.
ResetRepresents a reset button to reset form data to its default values.
List of Type Attributes

Basic Example of Changing Button Text in JavaScript

Change button text JavaScript – Using innerText

Start with a simple example. Here, we change the text of a button when the user clicks it.

buymeacoffee
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change button text JavaScript – Using innerText Code Example</title>
</head>
<body>
    <button id="myButton">Click me!</button>
    
    <script>
        document.getElementById('myButton').addEventListener('click', function() 
        {
            this.innerText = 'Humm... Button Clicked!';
        });
    </script>
</body>
</html>

Output

Change button text JavaScript – A simple code example

Using innerHTML

<script>
        document.getElementById('myButton').addEventListener('click', function() 
        {
            //this.innerHTML = 'Humm... Button Clicked!';
            this.innerHTML = "<b><i>Humm... Button Clicked!</i></b>";
        });
    </script>

Here we are using the same element. Just modified the script portion. So change accordingly to produce below change text output.

Output

Change button text JavaScript – Using innerHTML Method

Using textContent

<script>
        document.getElementById('myButton').addEventListener('click', function() 
        {
            this.textContent = "Humm... Button Clicked!";
        });
    </script>
JS MethodDescription
innerTextYou can change only text of the button.
innerHTMLYou can change the text with specific styles also.
textContentSimilar to innerText. But most preferred method to change only the text.
Common JS Methods

Note

innerText returns all text, including child elements contained by the element. innerHtml also returns all text along with html tags. To avoid confusion, always print the returned output into the console log.

Look at the below example to understand the differences clearly

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change button text JavaScript – Using innerText Code Example</title>
</head>
<body>
    <button id="myButton"><b>Click me!</b></button>
    
    <script>
        document.getElementById('myButton').addEventListener('click', function() 
        {
            console.log(this.innerText);
            console.log(this.innerHTML);
            console.log(this.textContent);

            this.innerText='Humm... Button Clicked!';
        });
    </script>
</body>
</html>

Output

Change button text JavaScript – JS Methods Differences

Code Explanation

In the first-click innerText method, return only the text part. innerHTML method returns text part along with bold HTML tag snippets. But in the second click, the innerText method replaces all elements within the button by the setter text only.

So what do we understand so far?

  1. If you want to change text and text styles, use innerHTML.
  2. If you want to keep the button text style, then also use innerHTML. 
  3. If the element has no other inner tags only then use innerText or textContent.

Step-by-Step Guide to Change Button Text in JavaScript

Follow the below steps to implement “Change button text JavaScript” correctly:

  • Get the Button Element: Use document.getElementById or document.querySelector to select the button.
  • Add an Event Listener: Use addEventListener to implement the click event. It’s a best practice instead of using the onclick inline method.
  • Change the Text: Set the textContent property of the button. You can also use the innerText or innerHTML method.

Methods to Select Button

You can use different methods to select your HTML button element. Here are some examples you can follow:

By ID:

let button = document.getElementById('myButton');

By Class:

let button = document.querySelector('.myButtonClass');

By Tag:

let button = document.querySelector('button');

Add Event Listeners

From my side, I always recommend adding event listeners instead of inline onclick events. Here is a code sample of how you can add event listeners to respond to an HTML control event:

button.addEventListener('click', function() {
    // Change the button text here
});

For dynamic applications some times you may need to add event listener dynamically by checking the HTML control type. In this case use JS event target type.

Frequent Use Cases

Here are some common scenarios where you need to change button text in JavaScript:

Form Submission:

document.getElementById('submitBtn').addEventListener('click', function() {
    this.textContent = 'Submitting...';
});

Toggle Button State:

document.getElementById('toggleBtn').addEventListener('click', function() {
    this.textContent = this.textContent === 'Start' ? 'Stop' : 'Start';
});

Use JS toggle function wisely.

Loading State:

document.getElementById('loadBtn').addEventListener('click', function() {
    this.textContent = 'Loading...';
});

Tips to Improve User Experience

  • Keep It Simple: Use clear and simple text to guide users.
  • Be Descriptive: Make sure that the button text accurately describes the action.
  • Feedback: Provide textual and visual feedback to the user, like changing the button color along with the text.

In case of Errors

If you are failed to change the text of a button then follow the below steps:

  • Correct Selection: Make sure that you select the button correctly and there is no spelling or case sensitivity issue.
  • Event Binding: Confirm that the event listener is correctly attached.
  • JavaScript Errors: Check the browser console for any JavaScript errors.

Note

If you are using <input type="button"> then use element.value to change the text. But innerText, innerHTML, and textContent are used for <button></button> element.

buymeacoffee

Conclusion

So far, we have mentioned all three methods and step-by-step guidelines to implement “Change button text JavaScript”. From now and on, you can easily change button text to enhance user interaction on your website. I hope that all of our above code examples will help you create dynamic and responsive web applications. Being with us and supporting us to grow.

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

🏋️‍♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨‍✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
«Previous
Next»

Good to Know

  • JavaScript Detect Cursor Position in Text Field: Must-Know Secrets!JavaScript Detect Cursor Position in Text Field: Must-Know Secrets!
  • Getvalue in JavaScript: Master It with This Simple GuideGetvalue in JavaScript Master It with This Simple Guide
  • How to Call JavaScript Function in HTML Without Onclick?How to Call JavaScript Function in HTML Without Onclick?
  • JavaScript Check and Uncheck Checkbox: Toggle in SecondsJavaScript Check and Uncheck Checkbox: Toggle in Seconds
  • 🎮 Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! 🏆Build a JavaScript Gamer Journal in 8 Lines
  • Toggle Function in JavaScript: 5 Common Pitfalls SolvedToggle Function in JavaScript: 5 Common Pitfalls Solved

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 5 Lesser-Known JavaScript Functions
    5 Lesser-Known JavaScript Functions to Boost Your Coding Efficiency
  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    🎮 Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! 🏆
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! 🐶
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright © 2024 CodersTechZone.com