Created
May 23, 2012 21:55
-
-
Save jonathantneal/2778077 to your computer and use it in GitHub Desktop.
Query Selector for IE
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
!('querySelectorAll' in document) && ('contains' in document.documentElement) && (function (window, document) { | |
var | |
documentHead = document.getElementsByTagName('head')[0], | |
querySelectorElement = document.createElement('style'), | |
querySelectorPrototypeElement = document.createElement('style'); | |
documentHead.insertBefore(querySelectorElement , documentHead.firstChild); | |
documentHead.insertBefore(querySelectorPrototypeElement, documentHead.firstChild); | |
function querySelectorAll(selector) { | |
var index = __querySelectorResult.length, result; | |
__querySelectorResult[index] = []; | |
querySelectorElement.styleSheet.cssText = selector + '{-ms-query-selector:expression(__querySelectorResult[' + index + '].push(this))}'; | |
scrollBy(0, 0); | |
querySelectorElement.styleSheet.cssText = ''; | |
result = __querySelectorResult.splice(index, 1)[0]; | |
if (this.parentNode) { | |
for (index = 0; result[index]; ++index) { | |
if (!this.contains(result[index])) { | |
result.splice(index--, 1); | |
} | |
} | |
} | |
return result; | |
} | |
function querySelector(selector) { | |
var results = querySelectorAll.call(this, selector); | |
return results && results[0]; | |
} | |
function matchesSelector(selector) { | |
var | |
results = querySelectorAll.call(document, selector), | |
resultsLength = results.length, | |
resultsIndex = -1; | |
while (++resultsIndex < resultsLength) { | |
if (results[resultsIndex] === this) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
window.__querySelectorResult = []; | |
document.querySelectorAll = querySelectorAll; | |
document.querySelector = querySelector; | |
document.matchesSelector = matchesSelector; | |
querySelectorPrototypeElement.styleSheet.cssText = '*{-ms-query-selector-prototype:expression(!this.querySelectorAll && (this.querySelectorAll = querySelectorAll) && (this.querySelector = querySelector) && (this.matchesSelector = matchesSelector))}'; | |
})(window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment