querySelector 和 querySelectorAll 方法是 W3C Selectors API 规范中定义的。他们的作用是根据 CSS 选择器规范,便捷定位文档中指定元素。
目前几乎主流浏览器均支持了他们。包括 IE8(含) 以上版本、 Firefox、 Chrome、Safari、Opera。
querySelector 和 querySelectorAll 方法很好用,可惜IE6、IE7不支持,怎么让IE6、IE7也支持querySelectorAll和querySelector这两个方法呢,请看下面的代码:
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; }; } // 用于在IE6和IE7浏览器中,支持Element.querySelectorAll方法 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; })();
参考资料:
qsa-polyfill-ie7.js
How to add querySelectorAll() function to Element for IE <= 7?
querySelector.polyfill.js