node
, if any.for
loop and Node.parentNode
to traverse the node tree upwards from the given node
.Node.nodeName
and String.prototype.toLowerCase()
to check if any given node is an anchor ('a'
).null
.const findClosestAnchor = node => {
for (let n = node; n.parentNode; n = n.parentNode)
if (n.nodeName.toLowerCase() === 'a') return n;
return null;
};
findClosestAnchor(document.querySelector('a > span')); // a
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️