parentNode vs. ParentElement

Should these be using all of one or the other?

Is there a way to determine which gets used where and when?

Code 1
https://jsfiddle.net/08a7bywp/1/

const thewrap = cover.parentNode.querySelector(".wrap");
const wrapper = evt.currentTarget.parentNode;

Code 2
https://jsfiddle.net/08a7bywp/

const thewrap = cover.parentElement.querySelector(".wrap");
const wrapper = evt.currentTarget.parentElement;

Code 3
https://jsfiddle.net/dt92v7q8/

const thewrap = cover.parentElement.querySelector(".wrap");
const wrapper = evt.currentTarget.parentNode;

Code 4
You have never changed these, they have always stayed as this.
https://jsfiddle.net/08a7bywp/2/

const thewrap = cover.parentNode.querySelector(".wrap");
const wrapper = evt.currentTarget.parentElement;

Because navigation such as nextElementSibling has become popular as it avoids unwanted nodes, parentElement is a slightly updated version of parentNode that does basically the same thing with a bit more protection.

Either works, but as elements are what we are dealing with, parentElement is the preferred way to go.

2 Likes

ok, so then this one it is.

Code 2
https://jsfiddle.net/08a7bywp/

function coverClickHandler(evt) {
    const cover = evt.currentTarget;
    const thewrap = cover.parentElement.querySelector(".wrap");
    hide(cover);
    show(thewrap);
  }
  function coverClickHandler(evt) {
    const wrapper = evt.currentTarget.parentElement;
    show(wrapper);
    initPlayer(wrapper);
  }

One of the main benefits of parentElement is when you are using a while loop to walk up each parent:

while (el.parentElement) {
  el = el.parentElement;
  // then check something
}

That code appropriately stops going up the parents when the HTML element is reached.

With parentNode, that goes further up from the HTML element to the document, which can cause issues, so you need further safety with parentNode.

while (el.parentNode.nodeType === 1) {
  el = el.parentNode;
  // then check something
}

Using parentElement gives more safety in that regard, where when going up from html it doesn’t give the document but gives null instead. That kind of safety with parentElement results in easier to understand code.

2 Likes

ok, now I know.

Don’t worry, it wasn’t just for you. There are many others here that can benefit from the information too.

1 Like

Helping one person do something or know something helps a lot more who see this.

2 Likes