Philip
Philip

Reputation: 779

How can I replicate something similar to querySelector in browsers like IE 7 and 6?

I've messed around with trying to detect how complex the query is (like if it's just an ID selector, it goes through getElementById instead and such) but this is clearly no way to do complex CSS queries and will probably fail on a certain few selectors.

So my question is to anyone who's done something similar, how did you end up replicating it for older browsers.

Upvotes: 2

Views: 1175

Answers (2)

Bob Fanger
Bob Fanger

Reputation: 29897

For predictable support for wide range of selectors go with Sizzle (or jQuery which uses Sizzle)

Otherwise you could use the snippet from: Creating a querySelector for IE that runs at “native speed” - Ajaxian

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);

        var result = [];
        for (var i in document.__qsResult) {
            result.push(document.__qsResult[i]);
        }
        return result;
    }

Upvotes: -1

rfunduk
rfunduk

Reputation: 30432

Use jQuery? Or at least a selector library like Sizzle. No point in reinventing the wheel.

Upvotes: 3

Related Questions