Haibara Ai Haibara Ai - 1 year ago 71
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?

Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download