Why should I use .parentNode instead of accessing a parent DOM element directly with .querySelector or .getElementById?


#1

Question

Why should I use .parentNode instead of accessing a parent DOM element directly with .querySelector or .getElementById?

Answer

We want to use .parentNode instead of .querySelector or .getElementById in the case that we don’t know/don’t care what a child node’s parent element is. For example, say we want to use .removeChild() to remove a child node; for this we will need both a reference to the child node and the parent, however in this example we only have a reference to the child node.
JS:

// In this example we wish to remove a child node using the ` .removeChild()` method
// The following line will select the child element that matches the `span` selector using the `.querySelector()` method

const childToRemove = document.querySelector('span');
// Remember that for this example we do not have a reference to the parent element
// Using the built in DOM property `.parentNode` we save a reference to the unknown parent node in our `parentNodeOfChildToRemove` variable (this is the parent of our `childToRemove` node) - this parent could be a `<div>`,`<p>`,` <h1>`, whatever

const parentNodeOfChildToRemove = childToRemove.parentNode;
// The following will remove the child of our unknown parent node using the `.removeChild()` method

parentNodeOfChildToRemove.removeChild(childToRemove);