querySelector:return the first matching Element node within the node's subtrees. If there is no such node, the method must return null.(回傳指定元素節點子樹中符合 selector 的第一個節點,若無符合則回傳 null)
querySelectorAll:return a NodeList containing all of the matching Element nodes within the node's subtrees, in document order. If there are no such nodes, the method must return an empty NodeList.(回傳符合 selector 的節點集合,採用文件順序;若無符合則回傳空集合)
var element = baseElement.querySelector(selectors); var elementList = baseElement.querySelectorAll(selectors);
當 baseElement 是 document 時,各瀏覽器的實作基本一致,沒什麼問題。但當 baseElement 是一個普通的 DOM 節點時,情況就開始有趣了。
<div class="test" id="testId">
<p><span>Test</span></p>
</div>
<script type="text/javascript">
var testElement = document.getElementById('testId');
var element = testElement.querySelector('.test span');
var elementList = document.querySelectorAll('.test span');
console.log(element); // <span>Test</span>
console.log(elementList); // 1
</script>
依 W3C 規格理解,這個例子應該回傳 element: null、elementList: []——因為作為 baseElement 的 testElement 子樹裡面並沒有符合 .test span 的節點(.test 就是它自己,不在子樹內)。
但瀏覽器的行為像是無視了 baseElement,只在乎 selector,此時 baseElement 幾乎等同 document。這與我們的預期不符。
嚴格說,這不是瀏覽器寫錯,而是規格文字容易被誤讀:「within the node's subtrees」指的是搜尋範圍限定在子樹,但 selector 本身是從文件根開始匹配的。所以 .test span 仍然能匹配到,只是結果必須落在子樹範圍內才算。理解這個區別,就能預測行為:selector 的匹配是全域的,結果的納入則受 baseElement 限制。
Andrew Dupont 發明了一個繞道手法:在 selector 前面指定 baseElement 的 id,藉此限制匹配範圍。這個方法被廣泛應用在各大框架中。
jQuery 的實作(1.6 片段):
var oldContext = context,
old = context.getAttribute("id"),
nid = old || id;
try {
if (!relativeHierarchySelector || hasParent) {
return makeArray(
context.querySelectorAll("[id='" + nid + "'] " + query), extra);
}
} catch (pseudoError) {}
finally {
if (!old) { oldContext.removeAttribute("id"); }
}
邏輯是:如果 baseElement 沒有 id,就先幫它設一個(Sizzle 用的是 sizzle 之類的暫定值),然後把 [id='xxx'] 拼在 selector 前面,做到範圍限制;最後因為這個 id 本來不屬於該元素,必須在 finally 中移除。用 finally 而非一般敘述來清理,是為了確保即使查詢過程拋出例外,暫時的 id 也不會殘留在 DOM 上——這是個值得學的細節。
Mootools 的實作:
var currentId = _context.getAttribute('id'), slickid = 'slickid__';
_context.setAttribute('id', slickid);
_expression = '#' + slickid + ' ' + _expression;
context = _context.parentNode;
手法與 jQuery 相同,只是暫用的 id 名叫 slickid__。
支援 querySelector/querySelectorAll 的環境:Firefox 3.5+、IE8+、Chrome 1+、Opera 10+、Safari 3.2+。其中 IE8 不支援以 object 作為 baseElement,且只認 CSS 2.1 選擇器。
這個問題在現代瀏覽器中已不存在——各家引擎都遵循同一份 Selectors API 標準,行為一致。但兩個觀念仍然值得記住:
一、querySelectorAll 回傳的是靜態的 NodeList,不是 live collection。這與 getElementsByClassName 的行為不同,迴圈中新增或刪除元素時要特別注意。
二、selector 的匹配是全域的。如果你真的想限定在子樹內,最清楚的寫法是把 selector 寫成後代關係,或先確認 baseElement 自身是否也在候選之列。
另外,如果查詢是高度重複的(例如每秒數次的捲動監聽中查元素),把結果快取在變數裡,或改用 ref 機制,比反覆查詢 DOM 有效得多。