innerHTML side effects?
I'm having some issues with a DOM element reference and I think I've tracked it down to having something to do with updating innerHTML.
In this example, at the first alert, the two variables refer to the same element, as expected. What's strange though is that after updating the innerHTML of the parent element (body), the two variables are supposedly different, despite not touching either.
<html>
<head>
<script type="text/javascript">
var load = function () {
var div1 = document.createElement('div');
div1.innerHTML = 'div1';
div1.id = 'div1';
document.body.appendChild(div1);
alert(div1 === document.getElementById('div1')); // true
document.body.innerHTML += '<div>div2</div>';
alert(div1 === document.getElementById('div1')); // false
};
</script>
</head>
<body onload="load();">
</body>
</html>
Using == instead of === produces the same results. I get the same results in Firefox 3.5 and IE6. Any idea what's causing the second alert to ev开发者_如何学Caluate to false?
WHen you get the innerHTML value of the body, add a string to it and put it back in the body, all elements in the body is recreated from the HTML string. What you have in the variable is a reference to an element that no longer exists in the page.
This is because ...
document.body.innerHTML += '<div>div2</div>';
... is not a true "append" .. it's a full replacement. Granted, the replacement is equal to the old content + the new content, the fact is that it is a new string which new DOM elements are built around.
精彩评论