npm install element-closest
#Element.closest method returns the closest element that matches a selector. It returns the element itself, one of its ancestor, or
null if there isn't any match.
element //=> Element or null
This is especially useful for delegating events.
The script is approximately 428 bytes, or 257 bytes when gzipped.
For immediate usage, add this script to your document:
For usage in Node, including Browserify and Webpack, run closest with your
const elementClosest = ;; // this is used to reference window.Element
|Browser||Native Support||Polyfill Support|
|Chrome||41+||4 - 40|
|Edge||15||12 - 14|
|Firefox||35+||3.5 - 34|
|Opera||28+||10 - 27|
|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
This library also polyfills
#Element.matches, which is widely supported but often vendor-prefixed.
element //=> boolean
matches is especially useful for short-handing
classList.contains with selectors.
const widget = document;if widget || widget// do something with the active widget