Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
221 views
Welcome To Ask or Share your Answers For Others

1 Answer

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";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...