开发者

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

开发者 https://www.devze.com 2023-01-19 03:58 出处:网络
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 s开发者_运维知识库uch) but this is clearly no way to d

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 s开发者_运维知识库uch) 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.


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


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;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号