node
.for
loop and Node.parentNode
to traverse the node tree upwards from the given node
.Element.matches()
to check if any given element node matches the provided selector
.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
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️