Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 918
tempy Avatar asked Oct 01 '12 19:10

tempy


People also ask

How do I change the text of a button in CSS?

HTML, CSS and JavaScript To change the font size of a button, use the font-size property.

How do I change the button text in Click react?

To change a button's text on click in React:Track the text of the button in a state variable. Set the onClick prop on the button element. When the button gets clicked, update the state variable.

How do you name a button in JavaScript?

The name property sets or returns the value of the name attribute of a button. The name attribute specifies the name of a button, and is used to reference form data after it has been submitted, or to reference the element in a JavaScript.


2 Answers

Change .text to .textContent to get/set the text content.

Or since you're dealing with a single text node, use .firstChild.data in the same manner.

Also, let's make sensible use of a variable, and enjoy some code reduction and eliminate redundant DOM selection by caching the result of getElementById.

function toggleText(button_id)  {    var el = document.getElementById(button_id);    if (el.firstChild.data == "Lock")     {        el.firstChild.data = "Unlock";    }    else     {      el.firstChild.data = "Lock";    } } 

Or even more compact like this:

function toggleText(button_id)  {    var text = document.getElementById(button_id).firstChild;    text.data = text.data == "Lock" ? "Unlock" : "Lock"; } 
like image 178
I Hate Lazy Avatar answered Oct 07 '22 22:10

I Hate Lazy


document.getElementById(button_id).innerHTML = 'Lock'; 
like image 27
elclanrs Avatar answered Oct 07 '22 20:10

elclanrs