IE6, IE7 compatible querySelectorAll and querySelector methods

The querySelector and querySelectorAll methods are defined in the W3C Selectors API specification. Their role is to easily locate the specified elements in the document according to the CSS selector specification.

Almost all major browsers currently support them. Including IE8 (inclusive) and above, Firefox, Chrome, Safari, Opera .

The querySelector and querySelectorAll methods are very useful, but unfortunately IE6 and IE7 do not support them. How can IE6 and IE7 also support the querySelectorAll and querySelector methods?

 

See the code below:

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

// Used in IE6 and IE7 browsers to support the Element.querySelectorAll method
var qsaWorker = (function () {
    var idAllocator = 10000;

    function qsaWorkerShim(element, selector) {
        var needsID = element.id === "";
        if (needsID) {
            ++idAllocator;
            element.id = "__qsa" + idAllocator;
        }
        try {
            return document.querySelectorAll("#" + element.id + " " + selector);
        }
        finally {
            if (needsID) {
                element.id = "";
            }
        }
    }

    function qsaWorkerWrap(element, selector) {
        return element.querySelectorAll(selector);
    }

    // Return the one this browser wants to use
    return document.createElement('div').querySelectorAll ? qsaWorkerWrap : qsaWorkerShim;
})(); 


can refer to the following example
// fix ie6 not suppot querySelectorAll bug
//var childElems = elem.querySelectorAll('img');

var childElems = qsaWorker(elem, 'img');

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325302758&siteId=291194637