Is anybody working on a jQuery.closest() equivalent in the DOM api?
Looks like the Selectors Level 2 draft adds matches()
equivalent to jQuery.is(), so native closest should be much easier to write. Has adding closest()
to Selectors come up?
Building off of Alnitak's answer. Here's the working current implementation with matchesSelector
which is now matches
in the DOM spec.
// get nearest parent element matching selector
function closest(el, selector) {
var matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
while (el) {
if (matchesSelector.call(el, selector)) {
break;
}
el = el.parentElement;
}
return el;
}
Browser support is great: http://caniuse.com/matchesselector