[javascript] How to change button text or link text in JavaScript?

I have this HTML button:

<button id="myButton" onClick="lock(); toggleText(this.id);">Lock</button>

And this is my toggleText JavaScript function:

function toggleText(button_id) 
{
   if (document.getElementById('button_id').text == "Lock") 
   {
       document.getElementById('button_id').text = "Unlock";
   }
   else 
   {
     document.getElementById('button_id').text = "Lock";
   }
}

As far as I know, button text (<button id="myButton">Lock</button>) is just like any link text
(<a href="#">Lock</a>). So the fact that it's a button doesn't matter. However, I can't access the button text and change it.

I tried ('button_id'), (button_id), == "Lock", == 'Lock', but nothing works.

How can I access and change a button text (not value) or a link text?

This question is related to javascript html button

The answer is


You can simply use:

document.getElementById(button_id).innerText = 'Your text here';

If you want to use HTML formatting, use the innerHTML property instead.


Remove Quote. and use innerText instead of text

function toggleText(button_id) 
{                      //-----\/ 'button_id' - > button_id
   if (document.getElementById(button_id).innerText == "Lock") 
   {
       document.getElementById(button_id).innerText = "Unlock";
   }
   else 
   {
     document.getElementById(button_id).innerText = "Lock";
   }
}

document.getElementById(button_id).innerHTML = 'Lock';

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click