Menu

gitpiper

findClosestMatchingNode javascript Code Snippet in 2024

browserintermediate

Last Updated: 21 April 2024

Finds the closest matching node starting at the given node.

  • Use a for loop and Node.parentNode to traverse the node tree upwards from the given node.
  • Use Element.matches() to check if any given element node matches the provided selector.
  • If no matching node is found, return 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

javascript snippet similar to findClosestMatchingNode 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! ✌️