Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 588
Haibara Ai Avatar asked Jul 16 '16 06:07

Haibara Ai


People also ask

Why is parentNode null?

The "Cannot read property 'parentNode' of null" error occurs when you access the parentNode property on a null value. To solve the error, run the JS script tag after the DOM elements have been created and make sure you're using the correct identifier.

What is the difference between parentElement and parentNode?

Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same.

What is parentNode parentNode in Javascript?

The read-only parentNode property of the Node interface returns the parent of the specified node in the DOM tree. Document and DocumentFragment nodes can never have a parent, so parentNode will always return null . It also returns null if the node has just been created and is not yet attached to the tree.

What is the difference between innerHTML and appendChild?

Answer : appendChild is used to insert new node in DOM. innerHTML is a property of DOM that allows to replace content of an element with different HTML, which automatically gets parsed into DOM nodes.


2 Answers

After resetting innerHTML property, browser parses the set contents and creates new elements. The test variable doesn't refer to the new element which also has test id. The original test element is 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); 
like image 94
undefined Avatar answered Sep 25 '22 23:09

undefined


val += b is actually the same as val = val + b. When written this way, it should be more obvious that you are recreating all elements inside parent.

If you want to append without destroying existing elements, use appendChild and not innerhtml.

like image 40
Matsemann Avatar answered Sep 25 '22 23:09

Matsemann