Today's question:
Find the nth parent of a given DOM element.
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;
}
Top comments (0)