Menu

gitpiper

findClosestMatchingNode javascript Code Snippet in 2023

browserintermediate

Last Updated: 1 February 2023

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 February 2023

Subscribe to our Newsletter

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

© 2023 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! ✌️