Files
30-seconds-of-code/snippets/find-closest-matching-node.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

751 B

title, tags, author, cover, firstSeen, lastUpdated
title tags author cover firstSeen lastUpdated
Find closest matching node browser chalarangelo flowering-hills 2021-04-22T08:45:39+03:00 2021-04-22T08:45:39+03:00

Finds the closest matching node starting at the given node.

  • Use a for loop and Node.parentNode to traverse the node tree upwards from the given node.
  • Use Element.matches() to check if any given element node matches the provided selector.
  • If no matching node is found, return null.
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