Skip to content

Home

Find closest anchor

Finds the anchor node closest to the given node, if any.

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

More like this

Start typing a keyphrase to see matching snippets.