views:

98

answers:

3

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 evaluate to false?

+3  A: 

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.

Guffa
Yes. If you would have used `document.createElement` and then `document.body.appendChild` for the second div, then the first div would remain in place.
Roland Bouman
+1  A: 

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.

Matt
A: 

http://jquery.com

kosmaks
jQuery can be used for a lot, but it does nothing towards answering the question...
Guffa
-1: Using jQuery may be useful to solve the questioner's problem eventually, but the jQuery homepage is unlikely to give specific helpful advice directly.
Paul Stephenson
jQuery is not the answer to all javascript issues. It is not ideal for applications for one reason or another (although it is great for many applications)
Sam Soffes