public
Last active

Element.prototype.matchesSelector shim

  • Download Gist
matchesSelector_shim.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
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;

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.