Search code examples
javascriptjqueryequivalent

JS equivalent of jQuery .is()


Is there a pure JS equivalent of jQuery .is() on modern browsers?

I know there is the querySelector method, but I want to check the node itself, rather than finding child nodes.


Solution

  • Looks like matchesSelector is what I want.

    https://developer.mozilla.org/en-US/docs/Web/API/Element.matches

    Polyfill is here:

    https://gist.github.com/jonathantneal/3062955

    this.Element && function(ElementPrototype) {
        ElementPrototype.matchesSelector = ElementPrototype.matchesSelector || 
        ElementPrototype.mozMatchesSelector ||
        ElementPrototype.msMatchesSelector ||
        ElementPrototype.oMatchesSelector ||
        ElementPrototype.webkitMatchesSelector ||
        function (selector) {
            var node = this, nodes = (node.parentNode || node.document).querySelectorAll(selector), i = -1;
    
            while (nodes[++i] && nodes[i] != node);
    
            return !!nodes[i];
        }
    }(Element.prototype);