641 B
641 B
title, tags
| title | tags |
|---|---|
| findClosestMatchingNode | browser,intermediate |
Finds the closest matching node starting at the given node.
- Use a
forloop andNode.parentNodeto traverse the node tree upwards from the givennode. - Use
Element.matches()to check if any given element node matches the providedselector. - 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