Explain Codes LogoExplain Codes Logo

How to change the button's text using JavaScript

javascript
event-handling
button-styles
performance-optimization
Anton ShumikhinbyAnton Shumikhin·Nov 8, 2024
TLDR

Improve a button's label promptly with JavaScript by targeting the button using document.getElementById('buttonId').innerText = 'New Text';. Make sure 'buttonId' correctly corresponds with your button's ID attribute and replace 'New Text' with your preferred text.

document.getElementById('buttonId').innerText = 'New Text';

Go beyond basics

When dealing with buttons, either <input type="button"> or standard <button>, their styles might differ, still, you handle them similarly.

Use the appropriate property

  • value property for input type buttons
  • textContent or innerText for typical button elements

For input type buttons:

// This *inputs* a new value into your button 😉 document.querySelector('#myInputButton').value = 'Click Me';

For button elements:

// Because every button yearns to be clicked... document.querySelector('#myButton').textContent = 'Click Here';

Put security and performance first

  • Choose textContent over innerText, better performance and no reflow
  • Shun innerHTML due to security risks like XSS (Cross-Site Scripting)

Event handling

Incorporate an event handler to your button and modify its text on the fly as it interacts with the user:

// We are 'clicking' into a new era of button labels, folks. document.getElementById('toggleButton').addEventListener('click', function() { this.textContent = this.textContent === 'Start' ? 'Stop' : 'Start'; });

Manage advanced scenarios

Changing button text as per conditions

Fabricate a function to toggle the button text using a filterStatus variable and conditional logic:

// Why have one button text when you can have two? Show off your JS skills. function showFilterItem() { var button = document.getElementById('filterButton'); var filterStatus = button.getAttribute('data-filter-status') === 'true'; button.textContent = filterStatus ? 'Show Less' : 'Show More'; button.setAttribute('data-filter-status', !filterStatus); }

Adopt responsive maintenance

Ensure your code is well-structured and named appropriately to make debugging easier and maintenance seamless.

Ensure cross-browser compatibility

Perform regular tests across different browsers to guarantee consistent functionality of your button text change.

Use event delegation

For larger applications with lots of buttons, use event delegation to manage events effectively:

// Not all heroes wear capes, some just delegate events. document.addEventListener('click', function(e) { if (e.target && e.target.matches("button.toggle")) { e.target.textContent = e.target.textContent === 'Expand' ? 'Collapse' : 'Expand'; } });