Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make document.querySelector work in IE6

I work on a website and I got a javascript function that doesn't work in Internet Explorer 6. I know

document.querySelector(selector)

only work in Internet Explorer 8+

What could I do to make it work in IE6?

(I don't try to make it work for the fun of it ;) )

like image 830
Lucien Dubois Avatar asked Dec 11 '22 01:12

Lucien Dubois


1 Answers

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.

like image 200
T.J. Crowder Avatar answered Dec 18 '22 13:12

T.J. Crowder