querySelectorAll 相比下面這些方法有什麼區別?html
(1)getElementsByTagNamenode
(2)getElementsByClassNameapi
(3)getElementsByName瀏覽器
var c1 = document.querySelectorAll('.b1 .c'); var c2 = document.getElementsByClassName('c'); var c3 = document.getElementsByClassName('b2')[0].getElementsByClassName('c');
try { var e1 = document.getElementsByClassName('1a2b3c'); var e2 = document.querySelectorAll('.1a2b3c'); } catch (e) { console.error(e.message); } console.log(e1 && e1[0].className); console.log(e2 && e2[0].className);
// Demo 1 var ul = document.querySelectorAll('ul')[0], lis = ul.querySelectorAll("li"); for(var i = 0; i < lis.length ; i++){ ul.appendChild(document.createElement("li")); } // Demo 2 var ul = document.getElementsByTagName('ul')[0], lis = ul.getElementsByTagName("li"); for(var i = 0; i < lis.length ; i++){ ul.appendChild(document.createElement("li")); }
The NodeList object returned by the querySelectorAll() method must be static ([DOM], section 8).
The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.因此,NodeList 本質上是一個動態的 Node 集合,只是規範中對 querySelectorAll 有明確要求,規定其必須返回一個靜態的 NodeList 對象。
document.querySelectorAll('a').toString(); // return "[object NodeList]" document.getElementsByTagName('a').toString(); // return "[object HTMLCollection]"
An HTMLCollection is a list of nodes. An individual node may be accessed by either ordinal index or the node's name or id attributes.
Note: Collections in the HTML DOM are assumed to be live meaning that they are automatically updated when the underlying document is changed.
var ul = document.getElementsByTagName('ul')[0], lis1 = ul.childNodes, lis2 = ul.children; console.log(lis1.toString(), lis1.length); // "[object NodeList]" 11 console.log(lis2.toString(), lis2.length); // "[object HTMLCollection]" 4