It seems that in Javascript, if you have a reference to some DOM element, and then modify the DOM by adding additional elements to document.body, your DOM reference becomes invalidated.
Consider the following code:
<html>
<head>
<script type = "text/javascript">
function work()
{
var foo = document.getElementById("foo");
alert(foo == document.getElementById("foo"));
document.body.innerHTML += "<div>blah blah</div>";
alert(foo == document.getElementById("foo"));
}
</script>
</head>
<body>
<div id = "foo" onclick='work()'>Foo</div>
</body>
</html>
When you click on the DIV, this alerts "true", and then "false." So in other words, after modifying document.body
, the reference to the DIV element is no longer valid. This behavior is the same on Firefox and MSIE.
Some questions:
Why does this occur? Is this behavior specified by the ECMAScript standard, or is this a browser-specific issue?
Note: there's another question posted on stackoverflow that seems to be referring to the same issue, but neither the question nor the answers are very clear.