17

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?

hurrymaplelad
  • 26,645
  • 10
  • 56
  • 76
  • It "should be easier" only if all browsers implement the method—they don't. :-( So a longhand method must be written anyway, I guess with feature detection for a `macthes` fork. It wouldn't be hard, but likely a little slow. – RobG Mar 11 '13 at 00:03
  • Yeah, [modernizer has an example](http://modernizr.com/docs/#prefixeddom) of falling back to vendor prefixed `matchesSelector`. – hurrymaplelad Mar 11 '13 at 00:10

6 Answers6

36

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

Web_Designer
  • 72,308
  • 93
  • 206
  • 262
Paul Irish
  • 47,354
  • 22
  • 98
  • 132
14

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-closest

Jonathan Raoult
  • 812
  • 7
  • 10
  • 2
    `element.closest` has landed in Chrome 41, not 40 (see https://crbug.com/422731#c7). And it has also landed in [Firefox 35](https://developer.mozilla.org/en-US/Firefox/Releases/35) – Rob W Dec 07 '14 at 16:52
  • You can also use a polyfill to use this function on older browsers, for example https://github.com/jonathantneal/closest – user1613797 May 14 '15 at 12:26
7

See the element.closest() documentation.

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()

if (window.Element && !Element.prototype.closest) {
  Element.prototype.closest = 
  function(s) {
      var matches = (this.document || this.ownerDocument).querySelectorAll(s),
          i,
          el = this;
      do {
          i = matches.length;
          while (--i >= 0 && matches.item(i) !== el) {};
      } while ((i < 0) && (el = el.parentElement)); 
      return el;
  };
}

But bear in mind that function implemented like this will not work properly on unattached tree (detached from document.documentElement root)

//Element.prototype.closestTest = function(s){...as seen above...};

var detachedRoot = document.createElement("footer");
var child = detachedRoot.appendChild(document.createElement("div"));
detachedRoot.parentElement; //null

child.closestTest("footer"); //null

document.documentElement.append(detachedRoot);
child.closestTest("footer"); //<footer>   

Though closest() that is implemented in Firefox 51.0.1 seems to work fine with detached tree

document.documentElement.removeChild(detachedRoot);
child.closestTest("footer"); //null
child.closest("footer"); //<footer>
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Pavlo D
  • 346
  • 2
  • 8
  • Seems to no longer be "experimental" according to MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest – Xenos Mar 09 '18 at 09:01
3

This sounds like it ought to be pretty easy, given the matches function, although that's not widely supported yet:

function closest(elem, selector) {
    while (elem) {
        if (elem.matches(selector)) {
            return elem;
        } else {
            elem = elem.parentElement;
        }
    }
    return null;
}

The trouble is, the matches function isn't properly supported. As it's still a relatively new API it's available as webkitMatchesSelector in Chrome and Safari, and mozMatchesSelector in Firefox.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • Yep, with `*MatchesSelector`, whipping up a closest using only native DOM gets easy. I'm more curious if there's any momentum behind adding `element.closest(selector)` as a native method of elements. – hurrymaplelad Mar 11 '13 at 00:13
  • @hurrymaplelad you'd probably have to join W3C and suggest it. I suspect they wouldn't bother though, given how easy it is to implement (per the code above). – Alnitak Mar 11 '13 at 00:15
1

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"

<html>
    <body>
        <foo>
            <bar>
                <a id="a">
                    <b id="b">
                        <c id="c"></c>
                    </b>
                </a>
            </bar>
         </foo>
    <script>
        var a = document.getElementById('a');
        var b = document.getElementById('b');
        var c = document.getElementById('c');
        alert(c.closest("a, b")==b);
    </script>
    </body>
</html>
Paritosh
  • 505
  • 5
  • 13
1

A little recursion will do the trick.

// get nearest parent element matching selector
var closest = (function() {
    var matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;

    return function closest(el, selector) {
        return !el ? null :
        matchesSelector.call(el, selector) ? el : closest(el.parentElement, selector);
    };
})();
Web_Designer
  • 72,308
  • 93
  • 206
  • 262
Finn Fitzsimons
  • 324
  • 3
  • 10
  • Or just `return element.tagName === 'HTML' ? null : element.matches(selector) ? element : closest(element.parentNode, selector);` ;) – yckart Aug 20 '15 at 17:09