Javascript javascript中的NodeList对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5501433/
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
NodeList object in javascript
提问by ppoliani
Can anyone tell me what kind of object the NodeList is. I read that it is an array-like object and that it can be accessed via bracket notation, for example var a = someNode.childNode[0];
. How is this possible since via bracket notation we can only access to the properties of an object, and as i know we can not have
谁能告诉我 NodeList 是什么类型的对象。我读到它是一个类似数组的对象,并且可以通过括号表示法访问它,例如var a = someNode.childNode[0];
. 这怎么可能,因为通过括号表示法我们只能访问对象的属性,而我知道我们不能
回答by brielov
A NodeList
is collection of DOM elements
. It's like an array (but it isn't). To work with it, you must turn it into a regular JavaScript array. The following snippet can get the job done for you.
ANodeList
是 的集合DOM elements
。它就像一个数组(但它不是)。要使用它,您必须将其转换为常规 JavaScript 数组。以下代码段可以为您完成工作。
const nodeList = document.getElementsByClassName('.yourClass'),
nodeArray = [].slice.call(nodeList);
UPDATE:
更新:
// newer syntax
const nodeList = Array.from(document.querySelectorAll('[selector]'))
// or
const nodeList = [...document.querySelectorAll('[selector]')]
回答by Tim Down
NodeList
is a host objectand is not subject to the usual rules that apply to native JavaScript objects. As such, you should stick to the documented API for it, which consists of a length
property and access to its members via square bracket property access syntax. You can use this API to create an Array
containing a snapshot of the NodeList's members:
NodeList
是一个宿主对象,不受适用于原生 JavaScript 对象的通常规则的约束。因此,您应该坚持使用文档化的 API,它包含一个length
属性,并通过方括号属性访问语法访问其成员。你可以使用这个 API 来创建一个Array
包含 NodeList 成员的快照:
var nodeList = document.getElementsByTagName("div");
var nodeArray = [];
for (var i = 0; i < nodeList.length; ++i) {
nodeArray[i] = nodeList[i];
}
回答by Torsten Becker
The NodeList is not a core Javascript object, it is provided by the Browser with the DOM. Think of a function which returns an interface to a dynamic or live object, so forEach() is not available, but you can convert it into a real array to have a snapshot with e.g.
NodeList 不是核心 Javascript 对象,它由浏览器随 DOM 提供。想想一个函数,它返回一个动态或活动对象的接口,所以 forEach() 不可用,但你可以将它转换成一个真正的数组,例如
// turns nodelist into an array to enable forEach
function toArray(list) {
var i, array = [];
for (i=0; i<list.length;i++) {array[i] = list[i];}
return array;
}
Details: http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-536297177
详情:http: //www.w3.org/TR/DOM-Level-3-Core/core.html#ID-536297177
回答by Torsten Becker
JavaScript is like Alcohol, it can coerce:
JavaScript 就像酒精一样,它可以强制:
var links = document.getElementsByTagName('a');
Array.prototype.slice.call(links).forEach(function(anchor, index, arr) {
anchor.addEventListener('click', onClickFN, false);
});
回答by Ionut Popa
NodeLists "live" which is to say that they are updated when the document structure changes such that they are always current with the most accurate information. In reality, all NodeList objects are queries that are run against the DOM whenever they are accessed.
NodeLists“实时”,也就是说当文档结构发生变化时它们会更新,以便它们始终具有最准确的信息。实际上,所有 NodeList 对象都是在访问时针对 DOM 运行的查询。
Any time you want to iterate over a NodeList, it's best to initialize a second variable with the length and then compare the iterator to that variable:
任何时候你想迭代 NodeList 时,最好用长度初始化第二个变量,然后将迭代器与该变量进行比较:
var divs = document.getElementsByTagName("div");
for (var i=0, lens=divs.length; i < len; i++){
var div = document.createElement("div");
document.body.appendChild(div);
}
NodeList is an array like structure but it's not actually an array. You can access array values through bracket notation.
NodeList 是一个类似数组的结构,但它实际上不是一个数组。您可以通过括号表示法访问数组值。
回答by Sudharshan
Node lists are often implemented as node iterators with a filter. This means that getting a property like length is O(n), and iterating over the list by re-checking the length will be O(n^2).
节点列表通常被实现为带有过滤器的节点迭代器。这意味着获得像 length 这样的属性是O(n),并且通过重新检查长度来迭代列表将是 O(n^2)。
var paragraphs = document.getElementsByTagName('p');
for (var i = 0; i < paragraphs.length; i++) {
doSomething(paragraphs[i]);
}
It is better to do this instead:
最好这样做:
var paragraphs = document.getElementsByTagName('p');
for (var i = 0, paragraph; paragraph = paragraphs[i]; i++) {
doSomething(paragraph);
}
This works well for all collections and arrays as long as the array does not contain things that are treated as boolean false.
这适用于所有集合和数组,只要数组不包含被视为布尔 false 的内容。
In cases where you are iterating over the childNodes you can also use the firstChild and nextSibling properties.
在迭代 childNodes 的情况下,您还可以使用 firstChild 和 nextSibling 属性。
var parentNode = document.getElementById('foo');
for (var child = parentNode.firstChild; child; child = child.nextSibling) {
doSomething(child);
}
回答by Mahmoud Felfel
Now in ES2015you can make use of Array.from
method which creates an Array instance from any array-like object, so this should work :
现在在ES2015 中,您可以使用Array.from
从任何类似数组的对象创建 Array 实例的方法,所以这应该可以工作:
const divList = Array.from( document.getElementsByTagName("div") );
For more information : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from
更多信息:https: //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from
回答by Willem van der Veen
Summary:
概括:
A NodeList
object is a data structure which represents a collection of Nodes. Nodes in the context of the DOM can be the following things:
甲NodeList
对象是一个数据结构,其表示节点的集合。DOM 上下文中的节点可以是以下内容:
- The document itself
- DOM elements (i.e. HTML/SVG elements)
- Text
- comments
- 文件本身
- DOM 元素(即 HTML/SVG 元素)
- 文本
- 注释
A NodeList
is notan array, however a NodeList
is an iterabledata structure which means we can loop over the values (i.e. the node items) using a for..of
loop. Furthermore are their some nice utility function on the prototype of the NodeList
which makes working with them more convenient.
阿NodeList
是不阵列,然而,NodeList
是一种迭代的数据结构,这意味着我们可以遍历使用的值(即各节点项目)for..of
循环。此外,它们的原型上还有一些不错的实用功能,NodeList
这使得使用它们更加方便。
Example:
例子:
const parent = document.querySelector('.parent');
const myNodeList1 = parent.childNodes; // this property is a Nodelist
console.log(myNodeList1 instanceof NodeList);
const myNodeList2 = document.querySelectorAll('.foo'); // this method returns a Nodelist
console.log(myNodeList2 instanceof NodeList);
// looping over the items of a nodelist
for (let el of myNodeList2) {
el.innerHTML = 'hi';
}
// getting the length of a nodeList
console.log(myNodeList2.length);
<div class="parent">
<div class="foo"></div>
<div class="foo"></div>
</div>
Here is what a Nodelist
looks like in the browser (chrome) devtools:
以下是Nodelist
浏览器 (chrome) devtools 中的外观:
You can access the elements of a NodeList
with the following notation:
您可以使用NodeList
以下符号访问 a 的元素:
myNodelist[0]; // grabs the first item of the NodeList
Because you are simply a property value of the object using a key. In this example the key of the property was the number zero, and value was the DOM element.
因为你只是一个使用键的对象的属性值。在这个例子中,属性的键是数字零,值是 DOM 元素。