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?
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.
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.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With