Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closest ancestor matching selector using native DOM?

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?

like image 374
hurrymaplelad Avatar asked Mar 10 '13 23:03

hurrymaplelad


1 Answers

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

like image 71
Paul Irish Avatar answered Oct 19 '22 17:10

Paul Irish