What is the minimum change to the last 3 lines of code that would make it work without adding or removing any lines of code?
<script>
function produceMessage(){
var msg= 'This should print';
return msg;
}
</script>
<div id="myDiv"> This should not print!</div>
<script>
var element=document.getElementById('myDiv').innerHTML;
var message= produceMessage();
element=message;</script>
For example this is not what I’m looking for since it combines the last three lines of code into one:
document.getElementById('myDiv').innerHTML= produceMessage();
from
to
.
The reason why your first one doesn’t work is because you are assigning the text from the
myDivelement tovar element. Strings are primitive, so they are passed by value, meaning that a copy of the text from.innerHTMLis copied intovar element.Rather than that, we want a reference to the HTML Element. Any non-primitive types are passed by reference by default in Javascript. To do that, we use
Now,
var elementpoints to the same object as thedocument.getElementById('myDiv'), rather than a different instance of the string from itsinnerHTML, meaning that when we modify theelement.innerHTML, we also modify the same object asdocument.getElementById('myDiv').innerHTML, which happens to be the one on the DOM (web page), rather than a new and different copy of the string.