Skip to content

Instantly share code, notes, and snippets.

@nanotronic
Forked from termi/matchesSelector_shim.js
Last active August 29, 2015 14:07
Show Gist options
  • Save nanotronic/8c08eacd13581d5a15ba to your computer and use it in GitHub Desktop.
Save nanotronic/8c08eacd13581d5a15ba to your computer and use it in GitHub Desktop.
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment