Skip to content

Home

Find closest matching node

Finds the closest matching node starting at the given node.

const findClosestMatchingNode = (node, selector) => {
  for (let n = node; n.parentNode; n = n.parentNode)
    if (n.matches && n.matches(selector)) return n;
  return null;
};

findClosestMatchingNode(document.querySelector('span'), 'body'); // body

More like this

Start typing a keyphrase to see matching snippets.