I wonder why I can't get document.getElementById("my_div").innerHTML update the DOM when I reassign the variable. For example:
<div id="my_div" onclick="clicky();"> Bye. </div> <script type="text/javascript" charset="utf-8"> function clicky() { var myDivValue = document.getElementById("my_div").innerHTML; myDivValue = "Hello"; console.log(myDivValue); } </script>
In the log, I see that the variable is redistributed when clicked, but innerHTML my_div remains unchanged. Why is this?
After several years of experience ...
For those who are just starting (like me) and asking about the same thing, there are two important concepts that you need to understand:
- Assign by reference: My error was that I thought that
var myDivValue = element.innerHTML would create a link / address for innerHTML, and every time I assigned a new value to this link, I could just update the content, but not that How does he work. - Assign by value: Instead, I simply made a copy of the
element.innerHTML value (which was empty) and assigned a value to myDivValue , then to myDivValue = "Hello"; I assigned a new value to myDivValue so of course it will never update element.innerHTML .
The incomprehensible part: when using the assignment operator ( = ) in JS, it is not obvious that you are either assigning a link or a value ( var referenceName = reference_to_thing versus var containerName = newValue )
As many have said in the answers, the correct way to do this is to assign a document.getElementById("my_div") element to myDiv :
var myDiv = document.getElementById("my_div")
And now that I have a link to an element named myDiv , I can update the innerHTML property whenever I like:
myDiv.innerHTML = "Hello" // innerHTML is now "Hello" myDiv.innerHTML = "Goodbye" // Changed it to "Goodbye"
javascript innerhtml
nipponese
source share