Haibara Ai Haibara Ai - 4 months ago 9
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>
<div id="test"></div>
</div>





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

Answer

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');
test.parentNode.appendChild(document.createTextNode('hello'));
console.log(test.parentNode);