var elem = document.getElementById("test"), frag = document.createDocumentFragment(); frag.appendChild(document.createElement("div")); elem.querySelector("p");// Element, querySelectorAll document.querySelector("div");// Document, querySelectorAll document.body.querySelector("div");// querySelectorAll frag.querySelector("div");// documentFragment, querySelectorAll
方法接收唯一的一個參數,該參數可為任意合法的CSS選擇器字符串。不過在IE8下,對於大部分的CSS3選擇器都不支持(只支持相鄰兄弟element1~element2;屬性選擇器
[attr^=val]
, [attr$=val]
,[attr*=val]
)。除此之外,如果想要在IE8下使用偽元素選擇器,需要用:,而不是CSS3規定的::(css3選擇器的瀏覽器支持參考:http://caniuse.com/#search=nth-of-type)。
Selectors API返回的內容是靜態的NodeList,而非實時更新的NodeList,這和get系列(早期的chrome等瀏覽器返回的是NodeList,現在已經改為HTMLCollection實例。NodeList和HTMLCollection最大的不同就是NodeList可包括文本、注釋等非元素節點,而HTMLCollection只包括元素節點)、document.images返回動態的集合(HTMLCollection)以及childNodes(NodeList)是不一樣的。
Selectors API雖然好用,不過在使用的時候還是需要注意一些問題。以下面代碼為例:
<body> <div id="test"><p>test</p></div> </body>
var ele = document.getElementById("test"); ele.querySelector("div p").length; // A jQuery(ele).find("div p").length; // B ele.querySelector("body p").length; // C jQuery(ele).find("body p").length; // D
對於代碼A,返回值為1,;代碼B,返回值為0。代碼C,返回值仍為1;代碼D,返回值為0。(結果適用於所有支持Selectors API的瀏覽器)
對於習慣使用jQuery的人來說,上面的結果可能有點接受不了。不過在規范中明確寫明:
Even though the method is invoked on an element, selectors are still evaluated in the context of the entire document. In the following example, the method will still match the
div
element's childp
element, even though thebody
element is not a descendant of thediv
element itself.var div = document.getElementById("bar"); var p = div.querySelector("body p");

// qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var old = context.id, id = context.id = "__sizzle__"; try { return makeArray( context.querySelectorAll( "#" + id + " " + query ), extra ); } catch(pseudoError) { } finally { if ( old ) { context.id = old; } else { context.removeAttribute( "id" ); } } }
不過,如果文檔中真的有的元素id為“__sizzle__”,這個方法應該就會悲劇了。
在zepto中,並沒有針對elem使用querySelector(All)時的特殊處理,So:
<!DOCTYPE html> <html> <head> <script src="http://zeptojs.com/zepto.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <div id="a"><div><p></p></div></div> </body> <script> var ele = Zepto("#a").find("body div div p"); alert(ele.length); // 1 </script> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <div id="a"><div><p></p></div></div> </body> <script> var ele =document.getElementById("a").querySelectorAll("*"); var chd = document.getElementById("a").childNodes; alert(ele.querySelectorAll); // undefined alert(chd.querySelectorAll); // undefined </script> </html>