Search code examples
javascriptonclickinnerhtml

Using .innerHTML from an onClick function


I am having trouble using .innerHTML within a javascript function called by clicking a button. For a brief flickering second I can see that the function is called, and the text changed, but then the text reverts.

<html>
<head>
</head>

<body>

<form>
     <input type="submit" value="Change the Text" onClick="change()">
</form>

<div id="ToBeChanged"> Hello, World </div>

<script>
 function change(){
     document.getElementById("ToBeChanged").innerHTML = "New Text"; 
 };
</script>

</body>
</html>

Of course, if I just use the .innerHTML outside of a function, it changes the text without any problems and does not revert to the old text. Is there a way to use .innerHTML to change text from the the onClick function? Or is there another way I should be accomplishing this task?


Solution

  • Oftentimes, when someone says that code in a submit button event handler does not work, the issue is that the button is causing the page to be reloaded, thus making you think that your code isn't working. In fact, your code is probably working, but then the page reloads immediately so you never see the code's effect.

    If that is indeed what is happening, you can prevent the page reload by changing your button to a regular button (not a submit button).

    <input type="button" value="Change the Text" onClick="change()">
    

    You could also leave the button as a submit button and prevent the default behavior for the button, but if you don't intend to submit a form, then better to just stop making it a submit button in the first place and just make it a regular button.