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

30秒学会 JavaScript 片段 – Find closest anchor

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

  • Use a for loop and Node.parentNode to traverse the node tree upwards from the given node.
  • Use Node.nodeName and String.prototype.toLowerCase() to check if any given node is an anchor ('a').
  • If no matching node is found, return 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

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