javascriptdominnerhtml

Why does manipulating innerHTML destroy the identities of the DOM nodes inside?


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.

var div1 = document.createElement('div');
div1.innerHTML = 'div1';
div1.id = 'div1';

document.body.appendChild(div1);
console.log(div1 === document.getElementById('div1')); // true

document.body.innerHTML += '<div>div2</div>';
console.log(div1 === document.getElementById('div1')); // false

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?


Solution

  • 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.