Menu

gitpiper

findClosestAnchor javascript Code Snippet in 2024

browserintermediate

Last Updated: 16 April 2024

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

javascript snippet similar to findClosestAnchor For You in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️