Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including element-closest with all npm packages installed. Try it out:

var elementClosest = require("element-closest")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

element-closest v2.0.2

Return the closest element matching a selector up the DOM tree

closest

Return the closest element matching a selector up the DOM tree

NPM Version Build Status Licensing Changelog Gitter Chat

closest is a polyfill for #Element.closest.

The #Element.closest method returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter. If there isn't such an ancestor, it returns null.

element.closest(selectorString) //=> element

This is especially useful for delegating events.

document.addEventListener('click', function (event) {
    // find nearest element up the tree that is an <a>
    var link = event.target.closest('a');

    if (link) {
        // do something with the <a>
        event.preventDefault();
    }
});

matches

The also polyfills #Element.matches, which is widely supported but often vendor-prefixed.

element.matches(selectorString) //=> boolean

matches is especially useful for short-handing 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

BrowserNative SupportPolyfill Support
Android532.2+
Blackberry7+
Chrome41+4 - 40
Edge12+
Firefox35+3.5 - 34
Internet Explorer8+
Opera28+10 - 27
Opera Mobile37+12+
Safari (iOS)9.2+3.2 - 8.4
Safari (MacOS)9.1+3.1 - 8

Internet Explorer 8

closest is especially useful for delegating events, but remember that Internet Explorer 8 does not support #Element.addEventListener.

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free