Get parents until element matches selector

JavaScript, Browser · Jan 6, 2021

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') {
    if (_el.matches(selector)) return parents;
    else _el = _el.parentNode;
  return [];
getParentsUntil(document.querySelector('#home-link'), 'header');
// [header, nav, ul, li]

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • JavaScript DOM Querying

    Learn how to query the DOM quickly and efficiently with this collection of JavaScript tips and tricks.

    Collection · 15 snippets

  • Get element ancestors

    Returns all the ancestors of an element from the document root to the given element.

    JavaScript, Browser · Jan 5, 2021

  • Get style for element

    Retrieves the value of a CSS rule for the specified element.

    JavaScript, Browser · Oct 19, 2020

  • Render DOM element

    Renders the given DOM tree in the specified DOM element.

    JavaScript, Browser · Oct 13, 2021