简体   繁体   中英

Issue with where to put .innerHTML in my JS code

I am doing a simple assignment for one of my modules and I've come into this problem for the 3rd or 4th time. My problem is that as my code shows below when I put the .innerHTML attribute on the first line it does not work at all and there is no error in the console window. When I place the it after the info.innerHTML on the second line it does work. I have asked a tutor and he is stuck on why this is happening

var info = document.getElementById("pOutput").innerHTML;
info = "Sum: " + sum + "<br>Average: " + avg;

var info = document.getElementById("pOutput");
info.innerHTML = "Sum: " + sum + "<br>Average: " + avg;

The second variation that you've included is correct but needs getElementById() instead of GetElementById().

The top lines are incorrect because you are overriding the variable info with your string, not writing it into innerHTML.

When you set info to innerHTML , it's getting the value. You need to set info to document.GetElementById("pOutput") , and then set info.innerHTML :

var info = document.getElementById("pOutput");
info.innerHTML = "Sum: " + sum + "<br>Average: " + avg;

The reason why this is happening is because in the first bit of code, you capture the value of the innerHTML property of the element. For example, if your element has <div></div> inside it, the value of info will be " <div></div> ". If you modified the innerHTML of the element after, the value of info would still be <div></div> . On the contrary, in the second bit of code, what you capture is a reference to the element. Therefore you can modify its properties and it will reflect on the element itself. The reason why this happens is explained here but to make it simple, some types (like strings and numbers) are copied as values and some other types (like Objects) are copied as references.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM