Created
May 18, 2012 09:49
-
-
Save connrs/2724353 to your computer and use it in GitHub Desktop.
IE7 querySelectorAll polyfill
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
if (!document.querySelectorAll) { | |
document.querySelectorAll = function(selector) { | |
var doc = document, | |
head = doc.documentElement.firstChild, | |
styleTag = doc.createElement('STYLE'); | |
head.appendChild(styleTag); | |
doc.__qsaels = []; | |
styleTag.styleSheet.cssText = selector + "{x:expression(document.__qsaels.push(this))}"; | |
window.scrollBy(0, 0); | |
return doc.__qsaels; | |
} | |
} |
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
document.querySelectorAll||(document.querySelectorAll=function(a){var b=document,c=b.documentElement.firstChild,d=b.createElement("STYLE");return c.appendChild(d),b.__qsaels=[],d.styleSheet.cssText=a+"{x:expression(document.__qsaels.push(this))}",window.scrollBy(0,0),b.__qsaels}); |
What selectors does this cover?
Nice trick. But it only seems to work in Quirks mode.
If I set a then it breaks ?
What ?! How it work exactly !
Error ! TypeError: Cannot set property 'cssText' of undefined
I need support for selectors like a:not(:last-child)
. This polyfill doesn't help me in that area.
This doesn't work for IE7 or down, you can still select all with jQuery.
Javascript
var elements = document.querySelectorAll('.all-elements-with-this-id');
jQuery:
var elements = $('.all-elements-with-this-id');
I'm not massively surprised it doesn't work. This was pulled off StackOverflow 8 years ago and it worked for a limited set of scenarios that I needed when building software for clients who still used IE7. If you aren't having any luck with this then I'd recommend looking for a real alternative to this!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is untested in IE6 so I haven't mentioned it here. With IE6, you would be limited by which CSS selectors you could take advantage of. I'm working on projects that have a (for progressively enhanced JS) baseline of IE7. Polyfilling querySelectorAll allows me to do some nice element event handlers in projects where jQuery and other selector libraries aren't permitted.