Last active
February 9, 2021 09:52
-
-
Save termi/2369850 to your computer and use it in GitHub Desktop.
Element.prototype.matchesSelector shim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
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
_hasOwnProperty ??