Files
30-seconds-of-code/snippets/js/s/get-parents-until.md
Angelos Chalaris 4d0316a062 Update covers
2023-05-07 22:25:00 +03:00

933 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Get parents until element matches selector snippet javascript
browser
chalarangelo orange-coffee-4 2021-01-06T13:04:18+02:00

Finds all the ancestors of an element up until the element matched by the specified selector.

  • Use Node.parentNode and a while loop to move up the ancestor tree of the element.
  • Use Array.prototype.unshift() to add each new ancestor to the start of the array.
  • Use 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]