Skip to content

Instantly share code, notes, and snippets.

@termi
Last active February 9, 2021 09:52
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save termi/2369850 to your computer and use it in GitHub Desktop.
Save termi/2369850 to your computer and use it in GitHub Desktop.
Element.prototype.matchesSelector shim
var _hasOwnProperty = Object.prototype.hasOwnProperty;
if(!Element.prototype.matchesSelector) {
Element.prototype.matchesSelector =
Element.prototype.matches ||
Element.prototype.webkitMatchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector || function(selector) {
if(!selector)return false;
if(selector === "*")return true;
if(this === document.documentElement && selector === ":root")return true;
if(this === document.body && selector === "body")return true;
var thisObj = this,
parent,
i,
str,
tmp,
match = false;
if(/^[\w#\.][\w-]*$/.test(selector) || /^(\.[\w-]*)+$/.test(selector)) {
switch (selector.charAt(0)) {
case '#':
return thisObj.id === selector.slice(1);
break;
case '.':
match = true;
i = -1;
tmp = selector.slice(1).split(".");
str = " " + thisObj.className + " ";
while(tmp[++i] && match) {
match = !!~str.indexOf(" " + tmp[i] + " ");
}
return match;
break;
default:
return thisObj.tagName && thisObj.tagName.toUpperCase() === selector.toUpperCase();
}
}
parent = thisObj.parentNode;
if(parent && parent.querySelector) {
match = parent.querySelector(selector) === thisObj;
}
if(!match && (parent = thisObj.ownerDocument)) {
tmp = parent.querySelectorAll(selector);
for (i in tmp ) if(_hasOwnProperty(tmp, i)) {
match = tmp[i] === thisObj;
if(match)return true;
}
}
return match;
}
}
if(!Element.prototype.matches)Element.prototype.matches = Element.prototype.matchesSelector;
@nsisodiya
Copy link

_hasOwnProperty ??

@sandstrom
Copy link

I'd use something like this instead:

(function(){
  if (!Element.prototype.matches) {
    var matches2 = function(selector) {
      return (this.matchesSelector || this.msMatchesSelector || this.mozMatchesSelector || this.webkitMatchesSelector || this.oMatchesSelector).call(this, selector);
    };

    Element.prototype.matches = matches2;
  }
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment