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
    dwProgressBar v2:  Stepping and Events

    dwProgressBar was a huge hit when it debuted. For those of you who didn't catch my first post, dwProgressBar is a MooTools 1.2-based progress bar which allows for as much flexibility as possible. Every piece of dwProgressBar can be controlled by CSS...

  • By
    Instagram For MooTools

    If you're still rocking an iPhone and fancy taking a photo every now and then, you'd be crazy not to be using an app called Instagram.  With Instagram you take the photos just as you would with your native iPhone camera app, but Instagram...

Discussion

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