I work on a website and I got a javascript function that doesn\'t work in Internet Explorer 6. I know
document.querySelector(selector)
onl
I strongly encourage you not to try to support IE6 any longer.
But you can add document.querySelector
and document.querySelectorAll
using this very clever trick from an Ajaxian article. The article actually gets it a bit wrong, it adds something called querySelector
that does querySelectorAll
instead. I've fixed the name here:
/*@cc_on
if (!document.querySelectorAll)
document.querySelectorAll = function(selector)
{
var head = document.documentElement.firstChild;
var styleTag = document.createElement("STYLE");
head.appendChild(styleTag);
document.__qsResult = [];
styleTag.styleSheet.cssText = selector + "{x:expression(document.__qsResult.push(this))}";
window.scrollBy(0, 0);
head.removeChild(styleTag);
var result = [];
for (var i in document.__qsResult)
result.push(document.__qsResult[i]);
return result;
}
@*/
Although I would never countenance using for-in
like that; details and alternatives in this other answer.
And by inference, querySelector
:
/*@cc_on
if (!document.querySelector)
document.querySelector = function(selector)
{
var head = document.documentElement.firstChild;
var styleTag = document.createElement("STYLE");
head.appendChild(styleTag);
document.__qsResult = [];
styleTag.styleSheet.cssText = selector + "{x:expression(document.__qsResult.push(this))}";
window.scrollBy(0, 0);
head.removeChild(styleTag);
// Return first result only
return document.__qsResult[0] || null;
}
@*/
Note that neither of the above adds Element#querySelector
or Element#querySelectorAll
(the versions that look only within an element), just document.querySelector
and document.querySelectorAll
. And you can't add the Element
versions on IE6 without adding them to each individual element, since IE6 doesn't support element prototypes.