Created
January 30, 2013 14:39
-
-
Save Fusselwurm/4673695 to your computer and use it in GitHub Desktop.
document.querySelector, document.querySelectorAll for IE7
This file contains 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
/*global document */ | |
/** | |
* define document.querySelector & document.querySelectorAll for IE7 | |
* | |
* A not very fast but small hack. The approach is taken from | |
* http://weblogs.asp.net/bleroy/archive/2009/08/31/queryselectorall-on-old-ie-versions-something-that-doesn-t-work.aspx | |
* | |
*/ | |
(function () { | |
var | |
style = document.createStyleSheet(), | |
select = function (selector, maxCount) { | |
var | |
all = document.all, | |
l = all.length, | |
i, | |
resultSet = []; | |
style.addRule(selector, "foo:bar"); | |
for (i = 0; i < l; i += 1) { | |
if (all[i].currentStyle.foo === "bar") { | |
resultSet.push(all[i]); | |
if (resultSet.length > maxCount) { | |
break; | |
} | |
} | |
} | |
style.removeRule(0); | |
return resultSet; | |
}; | |
// be rly sure not to destroy a thing! | |
if (document.querySelectorAll || document.querySelector) { | |
return; | |
} | |
document.querySelectorAll = function (selector) { | |
return select(selector, Infinity); | |
}; | |
document.querySelector = function (selector) { | |
return select(selector, 1)[0] || null; | |
}; | |
}()); |
Thanks this helped a lot! and answer my curiosity
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here I am eight years later as GitHub's "customize your pins" feature leads me to this place and the realization that my copy of this long-forgotten hack is my most-starred contribution to the world
…
…
because as recently as 2018, people still had to support IE7 ???