Thursday, July 6, 2023
HomeProgrammingJavaScript closest

JavaScript closest


With regards to discovering relationships between parts, we historically consider a top-down method. We are able to thank CSS and querySelector/querySelectorAll for that relationship in selectors. What if we need to discover a component’s mum or dad primarily based on selector?

To look up the ingredient tree and discover a mum or dad by selector, you should use HTMLElement‘s closest technique:

// Our pattern ingredient is an "a" tag that matches ul > li > a
const hyperlink = doc.querySelector('li a');
const listing = a.closest('ul');

closest appears up the ancestor chain to discover a matching mum or dad ingredient — the alternative of conventional CSS selectors. You’ll be able to present closest a easy or advanced selector to look upward for!


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments