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?
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?
A little recursion will do the trick.
Using element.closest() we can find Closest ancestor matching selector. This method takes selectors list as parameter and returns the closest ancestor. As per Rob's Comment this API will be available from chrome 41 and FF 35.
As explained in whatwg specs https://dom.spec.whatwg.org/#dom-element-closest
Example: The below HTML will show alert message "true"
Building off of Alnitak's answer. Here's the working current implementation with
matchesSelector
which is nowmatches
in the DOM spec.Browser support is great: http://caniuse.com/matchesselector
This sounds like it ought to be pretty easy, given the
matches
function, although that's not widely supported yet:The trouble is, the
matches
function isn't properly supported. As it's still a relatively new API it's available aswebkitMatchesSelector
in Chrome and Safari, andmozMatchesSelector
in Firefox.Seems like Chrome 40 will bring a native
element.closest()
method (http://blog.chromium.org/2014/12/chrome-40-beta-powerful-offline-and.html) specified here: https://dom.spec.whatwg.org/#dom-element-closestElement.closest()
its support
Implementing such function with Element.matches() seems not optimal in terms of performance, cause apparently matches() will make a call to querySelectorAll() every time you test a parent, while only one call is sufficient for the job.
Here's a polyfill for closest() on MDN. Note a single call to querySelectorAll()
But bear in mind that function implemented like this will not work properly on unattached tree (detached from document.documentElement root)
Though closest() that is implemented in Firefox 51.0.1 seems to work fine with detached tree