30秒学会 JavaScript 片段 · 2022年12月23日

30秒学会 JavaScript 片段 – Find closest matching node

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

翻译自:https://www.30secondsofcode.org/js/s/find-closest-matching-node