DEV Community

Shweta Kale
Shweta Kale

Posted on • Edited on

DOM Challenge #2 nth parent

Today's question:

Find the nth parent of a given DOM element.

Image description
If input is Div.6 & n is 2 we should output Div.2

Considerations:
1) What if n > number of parents?
In that case we return null.
2) n > 0

Approach:

Get all parentNodes of DOM and return (n-1)th element from array.

Code:

const parentList = (node)=>{
   let tempNode = node;
   const parentNodes = [];
   while(tempNode.parentElement){
     parentNodes.push(tempNode.parentElement);
    tempNode = tempNode.parentElement;
   }
   return parentNodes;
}

const getNthParent = (node, n) => {
   const parentNodes = parentList(node);
   if(n > parentNodes.length){
      return parentNodes[n-1];
   }
  return null;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more