Haibara Ai Haibara Ai - 6 months ago 13
HTML Question

After changing parentNode.innerHTML, can't access parentNode

Say I have the following DOM structure and scripts

var test = document.getElementById('test');
test.parentNode.innerHTML += 'hello';
console.log(test.parentNode); // null
console.log(document.getElementById('test').parentNode); // normal result

<div id="test"></div>

As above script says, the first outputs
while the second outputs the actual node, does anyone know why the first output
rather than the normal node?


By resetting innerHTML property, browser parses the set contents and creates new elements. The test variable doesn't refer to the new element that has test id. It's detached from the DOM and has no parent element. test and document.getElementById('test') refer to different DOM Element objects.

Use the createTextNode and appendChild methods instead and see the difference:

var test = document.getElementById('test');