Search code examples
javascripthtmlonclickbuttonclick

Difference between saving an element to a variable and just calling document.getElementByID()


I realize the title doesn't make a lot of sense, but I'm not sure how else to express the question I have. I am trying to learn about adding events to buttons in JavaScript, and I have run into a bug that I cannot figure out. Here are the two pieces of code (both of which are inside of a window.onload function):

This one works:

document.getElementById("button").onclick = function func() {
    document.getElementById("testParagraph").innerHTML = "I changed the text";
}

This one doesn't:

var button = document.getElementById("button");
button.onclick = document.getElementById("testParagraph").innerHTML = "I changed the text";

and here's the HTML:

<p id="testParagraph"> This <strong> is </strong> a test </p>
<button id="button">Run Test</button>

By work, I mean the first one shows the paragraph with "This is a test" until after I click the button, when it changes it to "I changed the text". The second one doesn't work because it loads "I changed the text" as soon as the page loads instead of waiting for the button to be clicked. Because I'm new to JavaScript, these look the same to me, I'm getting the button using its id and then adding an onclick event listener. It's just that the second one assigns the button to a variable and the first one just grabs it with getElementById. Both were run inside a window.onload function. Could someone help me see the difference?

EDIT: I changed the second piece of code to the following and it worked correctly.

var buttonX = document.getElementById("button");
buttonX.onclick = function clicked() {
    document.getElementById("testParagraph").innerHTML = "I changed the text";
}

Solution

  • You have to wrap your callback to onclick in a function. You can not just write the commands as you did

    var button = document.getElementById("button");
    button.onclick = function(){ 
      document.getElementById("testParagraph").innerHTML = "I changed the text"; 
    };
    

    Storing the reference to the element in a variable or not has no influence here.