Depending on how you declare the button, you need to either use innerHTML, or the childNodes, or the value property of the button.  Note: this tutorial has been tested with IE6 and Netscape 6.2 and 7, Firefox 1.04, and Opera 8 on the PC.  I don't know how it behaves on other browsers.

Button Declared with <input type="button">

To change the text of a button that has been declared with <input type="button"> tag: use the button's value property.  For example:

<input type="button" value="Button Text" id="myButton1"></input> 

To change the text of that button, we can use this code:

document.getElementById("myButton1").value="New Button Text";
Try it (this will execute the code above)

You can also type a text here, then click the button above:

If you try to change the text using innerHTML, IE6 will give : "Unknown Runtime Error;" and Netscape 7 simply won't change the text.  So, this code below does not work:

document.getElementById("myButton1").innerHTML="New Button Text";


Button Declared with <button>

Let's see an example first:

<button type="button" id="myButton2">Button Label</button>

In IE6 and Netscape 7 (I don't know about other browsers), the text can be changed in at least two ways:

You can also type a text here, then click the button above:

The innerHTML method has a problem when run on Netscape 6.2 and 7.02 on the PC (and possibly other versions).  The problem occurs if you try to change the text of a button more than once in the same session (using innerHTML).  For instance, below I change to the innerHTML of the button to a new text:

If I subsequently try to change the innerHTML again, the button will get messed up and becomes a small square like this:

For this reason, I recommend using the childNodes method instead.


A Functional Code


Here's a function that handles all cases above.  It checks if the button can be changed with the childNodes property first.  If not, then it will try again using the value property.  If that also fails, then it will use the innerHTML property (we use this as the last resort because some Netscape browsers has a problem with it - see above).   

function replaceButtonText(buttonId, text)
  if (document.getElementById)
    var button=document.getElementById(buttonId);
    if (button)
      if (button.childNodes[0])
      else if (button.value)
      else //if (button.innerHTML)

To call this function, pass the ID of the button element (buttonID) and the text to put into the button.

replaceButtonText('myButton1', 'new button text');

That will replace the text of the button with the id "myButton" with "new button text".


(C)2002 F. Permadi