How to make document.querySelector work in IE6

前端 未结 2 1358
抹茶落季
抹茶落季 2021-01-14 17:45

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

2条回答
  •  旧时难觅i
    2021-01-14 18:24

    You could use a polyfill, like this one, however still using IE6, is the IT analogue of necromancy.

    The mentioned polyfill is based on polyfill.js, which can be found here, this provides polyfills for a lot of ECMA 5 functions.

    I will post the current state of the script, maybe it will useful in the future (though I really hope, it won't be :) ):

    if (!document.querySelectorAll) {
        document.querySelectorAll = function (selectors) {
            var style = document.createElement('style'), elements = [], element;
            document.documentElement.firstChild.appendChild(style);
            document._qsa = [];
    
            style.styleSheet.cssText = selectors +
                    '{x-qsa:expression(document._qsa && document._qsa.push(this))}';
            window.scrollBy(0, 0);
            style.parentNode.removeChild(style);
    
            while (document._qsa.length) {
                element = document._qsa.shift();
                element.style.removeAttribute('x-qsa');
                elements.push(element);
            }
            document._qsa = null;
            return elements;
        };
    }
    
    if (!document.querySelector) {
        document.querySelector = function (selectors) {
            var elements = document.querySelectorAll(selectors);
            return (elements.length) ? elements[0] : null;
        };
    }
    

提交回复
热议问题