nipponese nipponese - 1 year ago 58
Javascript Question

Setting innerHTML: Why won't it update the DOM?

Wondering why I can't get

to update the DOM when I re-assign the variable. For example:

<div id="my_div" onclick="clicky();">
<script type="text/javascript" charset="utf-8">
function clicky() {
var myDivValue = document.getElementById("my_div").innerHTML;
myDivValue = "Hello";

In the log I can see the variable get re-assigned when I click, but the innerHTML of my_div remains unchanged. Why is this?

Answer Source

innerHTML evaluates to a string. I'm not sure why you would expect anything different. Consider this:

var a = 'foo'; // now a = 'foo'
var b = a; // now a = 'foo', b = 'foo'
b = 'bar'; // now a = 'foo', b = 'bar'

Re-assigning b doesn't change a.

Edited to add: In case it's not clear from the above, if you want to change innerHTML, you can just assign to it directly:

document.getElementById("my_div").innerHTML = "Hello";

You don't need, and can't use, an intermediary variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download