- querySelector 和 querySelectorAll 相比下面這些方法有什么區別?
getElementsByTagName
getElementsByClassName
getElementsByName
- 1. W3C 標准
querySelectorAll 屬於 W3C 中的 Selectors API 規范 。而 getElementsBy 系列則屬於 W3C 的 DOM 規范 。
- 2. 瀏覽器兼容
querySelectorAll 已被 IE 8+、FF 3.5+、Safari 3.1+、Chrome 和 Opera 10+ 良好支持 。
getElementsBy 系列,以最遲添加到規范中的 getElementsByClassName 為例,IE 9+、FF 3 +、Safari 3.1+、Chrome 和 Opera 9+ 都已經支持該方法了。
- 3. 接收參數
querySelectorAll 方法接收的參數是一個 CSS 選擇符。而 getElementsBy 系列接收的參數只能是單一的className、tagName 和 name。代碼如下 :
var c1 = document.querySelectorAll('.b1 .c'); var c2 = document.getElementsByClassName('c'); var c3 = document.getElementsByClassName('b2')0].getElementsByClassName('c');
需要注意的是,querySelectorAll 所接收的參數是必須嚴格符合 CSS 選擇符規范的。
- 4. 返回值
=querySelectorAll 返回的是一個 Static Node List,而 getElementsBy 系列的返回的是一個 Live Node List。
var qq1 = document.getElementsByClassName("qq"); var qq2 = document.querySelectorAll(".qq"); console.log(qq1); console.log(qq2);
看瀏覽器的返回結果
HTMLCollection [ <div.qq>, <div.qq>, <div.qq>, <div.qq> ]
NodeList [ <div.qq>, <div.qq>, <div.qq>, <div.qq> ]
NodeList 對象會包含文檔中的所有節點,如 Element、Text 和 Comment 等。
HTMLCollection 對象只會包含文檔中的 Element 節點。
所以在現代瀏覽器中,querySelectorAll 的返回值是一個靜態的 NodeList 對象,而 getElementsBy 系列的返回值實際上是一個 HTMLCollection 對象 。
- 5.在舉個例子
var qq1 = document.getElementsByClassName("qq"); var qq2 = document.querySelectorAll(".qq"); console.log(qq1); console.log(qq2); for(var i = 0; i < qq1.length; i++) { qq1[i].onclick = function() { this.parentNode.removeChild(this); console.log(qq1); } }
把qq1內容點擊刪除之后,結果如左邊的圖,再把上面代碼for循環里面的qq1改成qq2,連續點擊刪除之后結果如右邊的圖
Nodelist雖然html中的元素在瀏覽器界面刪除了,但是在數組中還是存在這幾個元素;
HTMLCollection,元素刪除,數組也刪除。
所以在現代瀏覽器中,querySelectorAll 的返回值是一個靜態的 NodeList 對象,而 getElementsBy 系列的返回值實際上是一個 HTMLCollection 對象 。
在一般情況中他們兩個是差不多的,但是如果你需要多次復雜操作取到的數組的話他們兩個會有所區別。
我也是在前幾天遇到的情況,后來查資料才知道他們有這種區別。希望對大家所幫助,不對的地方希望大神指點!!