4

I'm trying to change the text of a button using this code, but I'm not getting any reaction. This should be good, looking at everything I've read through - but it doesn't change the text. What am I doing wrong here?

<!DOCTYPE html>
<html>
<head>
    <script>
        function changeText() {
            document.getElementById('myButton').value = "New value";
        }
    </script>
</head>
<body>
    <button id="myButton" onclick="changeText()">Change my text!</button>
</body>
</html>
2
  • 2
    'myButton').innerHTML = "New value";. button don't have value Commented Oct 16, 2015 at 14:33
  • 1
    document.getElementById('myButton').textContent = "New value"; Commented Oct 16, 2015 at 14:35

3 Answers 3

8

You need to set the 'innerHTML' property instead:

function changeText() {
    document.getElementById('myButton').innerHTML= "New value";
}

You can specify a value on the button but it's not used very often. In your case you want to the text of the button to change. So innnerHTML is your friend. See this page for more details.

Also note that you could use 'innerText' in IE as well but it is not supported in Firefox (and probably not in some other as well). 'textContent' can also be an option but that one is not supported in older browsers (before 2011). So innerHTML is the safest option.

Sign up to request clarification or add additional context in comments.

Comments

3

Buttons can have a value but what is displayed is the HTML inside of the button, which is what you want to change. Better use innerHTML:

function changeText() {
    document.getElementById('myButton').innerHTML = "New value";
}

Comments

0

What the other answers said, plus this: buttons generated by the <input> element have a value! That may be where the confusion is coming from:

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

What you have is a:

<button>Button Text</button>

element, which is something else; hence innerHTML, not value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.