JavaScript closest

By  on  

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?

To look up the element tree and find a parent by selector, you can use HTMLElement's closest method:

// 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!

Recent Features

Incredible Demos

  • By
    Introducing MooTools Dotter

    It's best practice to provide an indicator of some sort when performing an AJAX request or processing that takes place in the background. Since the dawn of AJAX, we've been using colorful spinners and imagery as indicators. While I enjoy those images, I am...

  • By
    Create a Sexy Persistent Header with Opacity Using MooTools or jQuery

    I've been working with the Magento eCommerce solution a lot lately and I've taken a liking to a technique they use with the top bar within their administrative control panel. When the user scrolls below a specified threshold, the top bar becomes attached to the...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!