What is element-closest?
The element-closest npm package is a polyfill for the Element.closest() method, which allows you to find the closest ancestor of an element that matches a given CSS selector. This is particularly useful for ensuring compatibility with older browsers that do not support the native Element.closest() method.
What are element-closest's main functionalities?
Find closest ancestor
This feature allows you to find the closest ancestor of an element that matches a specified CSS selector. In this example, the closest ancestor of the element with the ID 'childElement' that has the class 'ancestorClass' is returned.
document.querySelector('#childElement').closest('.ancestorClass');
Other packages similar to element-closest
matches-selector
The matches-selector package provides a polyfill for the Element.matches() method, which checks if an element matches a given CSS selector. While it does not provide the same functionality as element-closest, it is often used in conjunction with it to ensure broader compatibility with older browsers.
dom-closest
The dom-closest package is another polyfill for the Element.closest() method. It offers similar functionality to element-closest, allowing you to find the closest ancestor of an element that matches a given CSS selector. It is a direct alternative to element-closest.
closest
Return the closest element matching a selector up the DOM tree
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)
This is especially useful for delegating events.
document.addEventListener('click', function (event) {
var link = event.target.closest('a');
if (link) {
event.preventDefault();
}
});
matches
The also polyfills #Element.matches
, which is
widely supported but often vendor-prefixed.
element.matches(selectorString)
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')) {
}
Browser compatibility
Browser | Native Support | Polyfill Support |
---|
Android | ✘ | 2.2+ |
Blackberry | ✘ | 7+ |
Chrome | 41+ | 4 - 40 |
Edge | ✘ | 12+ |
Firefox | 35+ | 3.5 - 34 |
Internet Explorer | ✘ | 8+ |
Opera | 28+ | 10 - 27 |
Opera Mini | ✘ | 5+ |
Safari (iOS) | 9 | 3.2 - 8.4 |
Safari (MacOS) | 9.2+ | 3.1 - 8 |
Internet Explorer 8
closest
is especially useful for delegating events, but remember that
Internet Explorer 8 does not support #Element.addEventListener
.