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
    jQuery Random Link Color Animations

    We all know that we can set a link's :hover color, but what if we want to add a bit more dynamism and flair? jQuery allows you to not only animate to a specified color, but also allows you to animate to a random color. The...

  • By
    Google-Style Element Fading Using MooTools or jQuery

    Google recently introduced an interesting effect to their homepage: the top left and top right navigation items don't display until you move your mouse or leave the search term box. Why? I can only speculate that they want their homepage as...

Discussion

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