jQuery HTMLCollection、NodeLists 和对象数组的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15763358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between HTMLCollection, NodeLists, and arrays of objects
提问by user1032531
I've always been confused between HTMLCollections, objects, and arrays when it comes to DOM. For instance...
当涉及到 DOM 时,我一直在 HTMLCollections、对象和数组之间感到困惑。例如...
- What is the difference between
document.getElementsByTagName("td")
and$("td")
? $("#myTable")
and$("td")
are objects (jQuery objects). Why is console.log also showing the array of DOM elements beside them, and are they not objects and not an array?- What is the elusive "NodeLists" all about, and how do I select one?
document.getElementsByTagName("td")
和 和有$("td")
什么区别?$("#myTable")
和$("td")
是对象(jQuery 对象)。为什么 console.log 还显示旁边的 DOM 元素数组,并且它们不是对象也不是数组?- 什么是难以捉摸的“NodeLists”,我该如何选择一个?
Please also provide any interpretation of the below script.
还请提供对以下脚本的任何解释。
Thank you
谢谢
[123,"abc",321,"cba"]=[123,"abc",321,"cba"]
{123:123,abc:"abc",321:321,cba:"cba"}=Object { 123=123, abc="abc", 321=321, more...}
Node= Node { ELEMENT_NODE=1, ATTRIBUTE_NODE=2, TEXT_NODE=3, more...}
document.links= HTMLCollection[a #, a #]
document.getElementById("myTable")= <table id="myTable">
document.getElementsByClassName("myRow")= HTMLCollection[tr.myRow, tr.myRow]
document.getElementsByTagName("td")= HTMLCollection[td, td, td, td]
$("#myTable")= Object[table#myTable]
$("td")= Object[td, td, td, td]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>Collections?</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
console.log('[123,"abc",321,"cba"]=',[123,"abc",321,"cba"]);
console.log('{123:123,abc:"abc",321:321,cba:"cba"}=',{123:123,abc:"abc",321:321,cba:"cba"});
console.log('Node=',Node);
console.log('document.links=',document.links);
console.log('document.getElementById("myTable")=',document.getElementById("myTable"));
console.log('document.getElementsByClassName("myRow")=',document.getElementsByClassName("myRow"))
console.log('document.getElementsByTagName("td")=',document.getElementsByTagName("td"));
console.log('$("#myTable")=',$("#myTable"));
console.log('$("td")=',$("td"));
});
</script>
</head>
<body>
<a href="#">Link1</a>
<a href="#">Link2</a>
<table id="myTable">
<tr class="myRow"><td>td11</td><td>td12</td></tr>
<tr class="myRow"><td>td21</td><td>td22</td></tr>
</table>
</body>
</html>
回答by Felix Kling
First I will explain the difference between NodeList
and HTMLCollection
.
首先,我将解释之间的差异NodeList
和HTMLCollection
。
Both interfaces are collectionsof DOM nodes. They differ in the methods they provide and in the type of nodes they can contain. While a NodeList
can contain any node type, an HTMLCollection
is supposed to only contain Element nodes.
An HTMLCollection
provides the same methods as a NodeList
and additionally a method called namedItem
.
两个接口是集合DOM节点。它们的不同之处在于它们提供的方法以及它们可以包含的节点类型。虽然 aNodeList
可以包含任何节点类型,但 anHTMLCollection
应该只包含 Element 节点。
AnHTMLCollection
提供与 a 相同的方法NodeList
,另外还有一个称为 的方法namedItem
。
Collections are always used when access has to be provided to multiple nodes, e.g. most selector methods (such as getElementsByTagName
) return multiple nodes or getting a reference to all children (element.childNodes
).
当必须为多个节点提供访问权限时,总是使用集合,例如,大多数选择器方法(例如getElementsByTagName
)返回多个节点或获取对所有子节点的引用(element.childNodes
)。
For more information, have a look at DOM4 specification - Collections.
有关更多信息,请查看DOM4 规范 - 集合。
What is the difference between
document.getElementsByTagName("td")
and$("td")
?
document.getElementsByTagName("td")
和 和有$("td")
什么区别?
getElementsByTagName
is method of the DOM interface. It accepts a tag name as input and returns a HTMLCollection
(see DOM4 specification).
getElementsByTagName
是DOM接口的方法。它接受一个标签名称作为输入并返回一个HTMLCollection
(参见DOM4 规范)。
$("td")
is presumably jQuery. It accepts any valid CSS/jQuery selector and returns a jQuery object.
$("td")
大概是jQuery。它接受任何有效的 CSS/jQuery 选择器并返回一个 jQuery 对象。
The biggest differences between standard DOM collections and jQuery selections is that DOM collections are typicallylive (not all methods return a live collection though), i.e. any changes to the DOM are reflected in the collections if they are affected. They are like a viewon the DOM tree, whereas jQuery selections are snapshots of the DOM tree in the moment the function was called.
标准 DOM 集合和 jQuery 选择之间的最大区别是 DOM 集合通常是实时的(尽管并非所有方法都返回实时集合),即,对 DOM 的任何更改都会反映在集合中,如果它们受到影响。它们就像DOM 树上的视图,而 jQuery 选择是调用函数时 DOM 树的快照。
Why is console.log also showing the array of DOM elements beside them, and are they not objects and not an array?
为什么 console.log 还显示旁边的 DOM 元素数组,并且它们不是对象也不是数组?
jQuery objects are array-likeobjects, i.e. they have numeric properties and a length
property (keep in mind that arrays are just objects themselves). Browsers tend to display arrays and array-like objects in a special way, like [ ... , ... , ... ]
.
jQuery 对象是类似数组的对象,即它们具有数字属性和一个length
属性(请记住,数组本身就是对象)。浏览器倾向于以特殊方式显示数组和类似数组的对象,例如[ ... , ... , ... ]
.
What is the elusive "NodeLists" all about, and how do I select one?
什么是难以捉摸的“NodeLists”,我该如何选择一个?
See the first part of my answer. You cannot selectNodeList
s, they are the resultof a selection.
请参阅我的答案的第一部分。您不能选择NodeList
s,它们是选择的结果。
As far as I know there is not even a way to create NodeList
s programatically (i.e. creating an empty one and adding nodes later on), they are only returned by some DOM methods/properties.
据我所知,甚至没有一种以NodeList
编程方式创建s的方法(即创建一个空的并稍后添加节点),它们仅由某些 DOM 方法/属性返回。
回答by Daniel Imms
0. What is the difference between an HTMLCollection
and a NodeList
?
0. anHTMLCollection
和 a 和有NodeList
什么不一样?
Here are some definitions for you.
这里有一些定义供您参考。
DOM Level 1 Spec - Miscellaneous Object Definitions:
Interface 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.
接口 HTMLCollection
HTMLCollection 是一个节点列表。可以通过序数索引或节点的名称或 id 属性访问单个节点。注意:HTML DOM 中的集合被假定为活动的,这意味着它们会在底层文档更改时自动更新。
Interface NodeList
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.
The items in the NodeList are accessible via an integral index, starting from 0.
接口节点列表
NodeList 接口提供了节点有序集合的抽象,而不定义或限制该集合的实现方式。DOM 中的 NodeList 对象是活动的。
NodeList 中的项目可以通过一个整数索引访问,从 0 开始。
So they can both contain live data which means that the DOM will update when their values do. They also contain a different set of functions.
所以它们都可以包含实时数据,这意味着 DOM 会在它们的值更新时更新。它们还包含一组不同的功能。
You will note if you inspect the console if you run your scripts that the table
DOM element contains both a childNodes
NodeList[2]
and a children
HTMLCollection[1]
. Why are they different? Because HTMLCollection
can only contain element nodes, NodeList also contains a text node.
您会注意到,如果您在运行脚本时检查控制台,table
DOM 元素同时包含 achildNodes
NodeList[2]
和 a children
HTMLCollection[1]
。他们为什么不同?因为HTMLCollection
只能包含元素节点,所以 NodeList 还包含一个文本节点。
1. What is the difference between document.getElementsByTagName("td")
and $("td")
?
1.之间有什么区别document.getElementsByTagName("td")
和$("td")
?
document.getElementsByTagName("td")
returns an array of DOM elements (a NodeList
), $("td")
is called a jQuery object which has the the elements from document.getElementsByTagName("td")
on its properties 0
, 1
, 2
, etc. The main difference is that the jQuery object is a little slower to retrieve but gives access to all the handy jQuery functions.
document.getElementsByTagName("td")
返回DOM元件的阵列(一NodeList
),$("td")
被称为jQuery对象从具有所述元件document.getElementsByTagName("td")
上其属性0
,1
,2
等,主要的区别是,jQuery对象较慢检索一点点,但可以访问所有的方便jQuery 函数。
2. $("#myTable")
and $("td")
are objects (jQuery
objects). Why is console.log
also showing the array of DOM elements beside them, and are they not objects and not an array?
2.$("#myTable")
和$("td")
是对象(jQuery
objects)。为什么console.log
还在它们旁边显示 DOM 元素数组,它们不是对象而不是数组?
They are objects with their properties 0
, 1
, 2
, etc. set to the DOM elements. Here's a simple example: of how it works:
他们对自己的属性的对象0
,1
,2
等一系列的DOM元素。这是一个简单的例子:它是如何工作的:
var a = {
1: "first",
2: "second"
}
alert(a[1]);
3. What is the elusive "NodeLists" all about, and how do I select one?
3. 什么是难以捉摸的“NodeLists”,我该如何选择一个?
You have been retrieving them in your code, getElementsByClassName
and getElementsByTagName
both return NodeList
s
您一直在代码中检索它们,getElementsByClassName
并且getElementsByTagName
都返回NodeList
s
回答by Sun
Additional note
附加说明
What is the difference between a HTMLCollection and a NodeList?
HTMLCollection 和 NodeList 有什么区别?
A HTMLCollectioncontains only element nodes (tags) and a NodeListcontains all nodes.
一的HTMLCollection只包含元素节点(标签)和节点列表包含了所有的节点。
There are four node types:
有四种节点类型:
- element node
- attribute node
- text node
- comment node
- 元素节点
- 属性节点
- 文本节点
- 评论节点
Whitespace inside elements is considered as text, and text is considered as nodes.
元素内的空白被视为文本,文本被视为节点。
Consider the following:
考虑以下:
<ul id="myList">
<!-- List items -->
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
<li>List item 5</li>
</ul>
Whitespace: <ul id="myList"> <li>List item</li></ul>
空格: <ul id="myList"> <li>List item</li></ul>
No whitespace: <ul id="myList"><li>List item</li></ul>
没有空格: <ul id="myList"><li>List item</li></ul>
回答by karaxuna
$("td")
is extended jQuery object and it has jQuery methods, it returns jquery object that contains array of html objects. document.getElementsByTagName("td")
is raw js method and returns NodeList. See this article
$("td")
是扩展的 jQuery 对象,它具有 jQuery 方法,它返回包含 html 对象数组的 jquery 对象。document.getElementsByTagName("td")
是原始 js 方法并返回 NodeList。看这篇文章
回答by S.Serpooshan
The NodeListobjects are collections of Node's, returned for example by x.childNodesproperty or document.querySelectorAll()method. In some cases, the NodeList is live, which means that changes in the DOM automatically update the collection! For example, Node.childNodes is live:
该节点列表对象是节点的集合,通过X返回例子。childNodes属性或document.querySelectorAll()方法。在某些情况下, NodeList 是live,这意味着 DOM 中的更改会自动更新集合!例如,Node.childNodes 已上线:
var c = parent.childNodes; //assume c.length is 2
parent.appendChild(document.createElement('div'));
//now c.length is 3, despite the `c` variable is assigned before appendChild()!!
//so, do not cache the list's length in a loop.
But in some other cases, the NodeList is static, where any changes in the DOM does not affect the content of the collection. querySelectorAll()returns a static NodeList.
但在其他一些情况下, NodeList 是static,其中 DOM 中的任何更改都不会影响集合的内容。querySelectorAll()返回一个静态 NodeList。
The HTMLCollectionis a live and orderedcollection of elements (it is automatically updated when the underlying document is changed). It can be result of properties like as childrenor methods like as document.getElementsByTagName(), and could only have HTMLElement'sas their items.
该的HTMLCollection是一个活的和有序的元素集合(在底层的文件被更改,自动更新)。它可以是像子项这样的属性或像document.getElementsByTagName()这样的方法的结果,并且只能将HTMLElement作为它们的项。
HTMLCollection also exposes its members directly as properties by both name and index:
HTMLCollection 还通过名称和索引将其成员直接公开为属性:
var f = document.forms; // this is an HTMLCollection
f[0] === f.item(0) === f.myForm //assume first form id is 'myForm'
The HTMLElement is just one type of Nodes:
HTMLElement 只是一种类型的节点:
The Node can be several types. Most important ones are as following:
节点可以是多种类型。最重要的如下:
- element (1): An Element node such as
<p>
or<div>
. - attribute (2): An Attribute of an Element. The element attributes are no longer implementing the Node interface in DOM4 specification!
- text (3): The actual Text of Element or Attribute.
- comment (8): A comment node.
- document (9): A document node.
- element (1):一个 Element 节点,例如
<p>
或<div>
。 - 属性(2):元素的属性。元素属性不再实现 DOM4 规范中的 Node 接口!
- text (3):元素或属性的实际文本。
- 评论(8):评论节点。
- 文档(9):一个文档节点。
So, a big difference is that HTMLCollection contains only HTMLElements but NodeList also contains the comments, white-space texts (carriage return chars, spaces..), etc. Check it as in following snippet:
所以,一个很大的区别是 HTMLCollection 只包含 HTMLElements,但 NodeList 还包含注释、空白文本(回车符、空格..)等。请按照以下代码段检查它:
function printList(x, title) {
console.log("\r\nprinting "+title+" (length="+x.length+"):");
for(var i=0; i<x.length; i++) {
console.log(" "+i+":"+x[i]);
}
}
var elems = document.body.children; //HTMLCollection
var nodes = document.body.childNodes; //NodeList
printList(elems, "children [HTMLCollection]");
printList(nodes, "childNodes [NodeList]");
<div>para 1</div><!-- MyComment -->
<div>para 2</div>
Both HTMLCollection and NodeList contain the lengthproperty you can use to loopover their items. Don't use for...in or for each...in to enumerate the items in NodeLists, since they will also enumerate its length and item properties and cause errors if your script assumes it only has to deal with element objects. Also, for..in is not guaranteed to visit the properties in any particular order.
HTMLCollection 和 NodeList 都包含长度属性,您可以使用它来循环它们的项目。不要使用 for...in 或 for each...in 来枚举 NodeLists 中的项目,因为如果您的脚本假定它只需要处理元素对象,它们也会枚举其长度和项目属性并导致错误。此外,不保证 for..in 以任何特定顺序访问属性。
for (var i = 0; i < myNodeList.length; i++) {
var item = myNodeList[i];
}