jQuery被開發者如此的青睐和它強大的選擇器有很大關系,比起笨重的document.getElementById、document.getElementByName… ,查找元素很友善,其實W3C中提供了querySelector和querySelectorAll查詢接口已經實作了類似功能。
其實這兩個方法看名字就能明白什麼意思,不過還是引用一下W3C的解釋
querySelector:return the first matching Element node within the node’s subtrees. If there is no such node, the method must return null .(傳回指定元素節點的子樹中比對選擇器的集合中的第一個元素,如果沒有比對傳回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. (按文檔順序傳回指定元素節點的子樹中比對選擇器的元素集合,如果沒有比對傳回空集合)
從定義可以看到Document和Element都實作了NodeSelector接口。即這三種類型的元素都擁有者兩個方法。querySelector和querySelectorAll的參數是CSS選擇器字元串。差別在于querySelector傳回的是一個第一個比對元素,querySelectorAll傳回的一個所有比對元素集合(NodeList)。
如果使用過jQuery或者了解CSS,這兩個方法使用很簡單,傳入選擇器即可


确實很好用,但是浏覽器對Element.querySelector和Element.querySelectorAll的實作有錯誤,看個例子


按照我們的了解span因該是搜尋test内部祖先元素為div的span元素,但是其祖先必須在test内部,而不能包括test本身甚至test的父元素,是以應該傳回空基赫才對,但是浏覽器會傳回
大神Andrew Dupont提出了一種方法修複這個bug,被廣泛應用到各個架構中,在selector前面指定調用元素的id,限制比對範圍。在jQuery中大概是這麼個意思


這樣做其實是給搜尋加了一層id的限制,巧妙的利用了這個bug,得到正确結果
雖然有些問題,但瑕不掩瑜,這麼好用的兩個方法咋沒火呢?浏覽器相容性。。。其實比起一些HTML5和CSS3的特性來說這兩個方法還沒那麼讓人絕望,因為IE8都已經支援了,其它各個主力主流浏覽器自然是實作了。
IE8+
Firefox
Chrome
Safari
Opera
Android
是以騷年們如果你是針對Mobile web優化,不要引用jQuery了,直接使用這兩個方法吧
本文轉自魏瓊東部落格園部落格,原文連結:http://www.cnblogs.com/dolphinX/p/3354318.html,如需轉載請自行聯系原作者