Finds all the ancestors of an element up until the element matched by the specified selector.
Node.parentNode
and a while
loop to move up the ancestor tree of the element.Array.prototype.unshift()
to add each new ancestor to the start of the array.Element.matches()
to check if the current element matches the specified selector
.const getParentsUntil = (el, selector) => {
let parents = [],
_el = el.parentNode;
while (_el && typeof _el.matches === 'function') {
parents.unshift(_el);
if (_el.matches(selector)) return parents;
else _el = _el.parentNode;
}
return [];
};
getParentsUntil(document.querySelector('#home-link'), 'header');
// [header, nav, ul, li]
JavaScript, Browser
Returns all the ancestors of an element from the document root to the given element.
JavaScript, Browser
Retrieves the value of a CSS rule for the specified element.
JavaScript, Browser
Finds the distance from a given element to the top of the document.