Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Get the closest element matching a selector up the DOM tree
JavaScript
branch: master
Failed to load latest commit information.
.editorconfig Initial commit
.jshintrc Initial commit
LICENSE.md Initial commit
README.md
bower.json Release v1.0.0
closest.js Code refactoring
closest.legacy.js Prefix detection

README.md

closest

closest returns the first (starting at element) inclusive ancestor that matches selectors, and null otherwise.

element = baseElement.closest(selectors);

closest tests the element itself for a selector match and then traverses up through its ancestors in the DOM tree until a successful selector match is found.

This is especially useful for delegating events.

document.addEventListener('click', function (event) {
    // get the closet anchor that has been clicked
    var a = event.target.closest('a');

    if (a) {
        // do something with the anchor
    }
});

matches

closest also polyfills matches. matches returns true if the element would be selected by the specified selector string; otherwise, returns false.

result = element.matches(selectorString);

matches is especially useful for shorthanding hasAttribute or classList.contains with selectors.

var widget = document.querySelector('.custom-widget');

if (widget.matches('[data-active]') || widget.matches('.widget--active')) {
    // do something with the active widget
}

Browser compatibility

matches and closest will work in Android 2.2+, Blackberry 7+, Chrome, Firefox 3.6+, Internet Explorer 9+, iOS Safari 4+, Opera 11.5+, and Safari 5+.

The legacy version extends support to Firefox 3.5+, Internet Explorer 8+, iOS Safari 3.2+, Opera 10+, Opera Mini 5+, and Safari 3.1+.

Those are really old browsers, and I don’t see a usecase for IE8 compatibility, which is why it is packaged separately. closest is especially useful when delegating events, and Internet Explorer 8 does not support addEventListener, and attachEvent is an insufficient fallback, as it fires events in the reverse order they are added (read: the opposite order of what you expect and addEventListener).

Prollyfill status

If you like closest and would like to it in a real DOM standard, convince Anne van Kesteren to add it to the DOM Standard.

UPDATE: Anne van Kesteren has added it to the DOM Living Standard. We will track Chrome, Opera, Firefox, and Safari as they implement it.

According to caniuse, matches has wide adoption, from IE9 to Firefox 3.6 to iOS4. It is prefix-free in Chrome 34. Nothing like closest exists existed outside of libraries like jQuery.

Chris Coyier’s excellent blog post Links with Inline SVG, Staying on Target with Events highlights the need for something like closest. After reading it, I decided to throw this together.


closest.js is 429B or 210B minified + gzipped. closest.legacy.js is 688B or 270B minified + gzipped.

Something went wrong with that request. Please try again.