JavaScript Mapping Library
When it comes to finding relationships between elements, we traditionally think of a top-down approach. We can thank CSS and querySelector/querySelectorAll for that relationship in selectors. What if we want to find an element’s parent based on selector?
querySelector
querySelectorAll
To look up the element tree and find a parent by selector, you can use HTMLElement‘s closest method:
HTMLElement
closest
// Our sample element is an "a" tag that matches ul > li > a const link = document.querySelector('li a'); const list = a.closest('ul');
closest looks up the ancestor chain to find a matching parent element — the opposite of traditional CSS selectors. You can provide closest a simple or complex selector to look upward for!
parent
The post JavaScript closest appeared first on David Walsh Blog.
David Walsh Blog
You must be logged in to post a comment.
This site uses Akismet to reduce spam. Learn how your comment data is processed.