JavaScript 中的 NodeList 对象

发布于 2024-10-28 19:41:13 字数 145 浏览 1 评论 0原文

谁能告诉我 NodeList 是什么类型的对象。我读到它是一个类似数组的对象,可以通过括号表示法访问它,例如 var a = someNode.childNode[0];。这怎么可能,因为通过括号表示法我们只能访问对象的属性,而且据我所知我们不能拥有

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

╰◇生如夏花灿烂 2024-11-04 19:41:13

NodeList 是 DOM 元素的集合。它就像一个数组(但事实并非如此)。要使用它,您必须将其转换为常规 JavaScript 数组。以下代码片段可以为您完成工作。

const nodeList = document.getElementsByClassName('.yourClass'),
      nodeArray = [].slice.call(nodeList);

更新:

// newer syntax
const nodeList = Array.from(document.querySelectorAll('[selector]'))

// or
const nodeList = [...document.querySelectorAll('[selector]')]

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.

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]')]
〃安静 2024-11-04 19:41:13

NodeList 是一个宿主对象,不受适用于本机 JavaScript 对象的常见规则的约束。因此,您应该坚持使用已记录的 API,它由 length 属性组成,并通过方括号属性访问语法对其成员进行访问。您可以使用此 API 创建一个包含 NodeList 成员快照的 Array

var nodeList = document.getElementsByTagName("div");
var nodeArray = [];
for (var i = 0; i < nodeList.length; ++i) {
    nodeArray[i] = nodeList[i];
}

NodeList is a host object and 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:

var nodeList = document.getElementsByTagName("div");
var nodeArray = [];
for (var i = 0; i < nodeList.length; ++i) {
    nodeArray[i] = nodeList[i];
}
眉目亦如画i 2024-11-04 19:41:13

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;
}

详细信息: http://www.w3.org/TR/DOM-Level-3-Core/core .html#ID-536297177

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.

// 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

对你的占有欲 2024-11-04 19:41:13

JavaScript 就像酒精一样,它可以强制:

var links = document.getElementsByTagName('a');
Array.prototype.slice.call(links).forEach(function(anchor, index, arr) {
  anchor.addEventListener('click', onClickFN, false);
});

JavaScript is like Alcohol, it can coerce:

var links = document.getElementsByTagName('a');
Array.prototype.slice.call(links).forEach(function(anchor, index, arr) {
  anchor.addEventListener('click', onClickFN, false);
});
故事还在继续 2024-11-04 19:41:13

NodeLists“实时”,也就是说,当文档结构发生变化时,它们会更新,以便它们始终具有最准确的信息。实际上,所有 NodeList 对象都是在访问时针对 DOM 运行的查询。

每当您想要迭代 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 是一个类似数组的结构,但它实际上不是一个数组。您可以通过括号表示法访问数组值。

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.

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:

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.

栖迟 2024-11-04 19:41:13

节点列表通常被实现为带有过滤器的节点迭代器。这意味着获取像长度这样的属性是O(n),并且通过重新检查长度来迭代列表将为 O(n^2)。

var paragraphs = document.getElementsByTagName('p');
for (var i = 0; i < paragraphs.length; i++) {
  doSomething(paragraphs[i]);
}

最好这样做:

var paragraphs = document.getElementsByTagName('p');
for (var i = 0, paragraph; paragraph = paragraphs[i]; i++) {
   doSomething(paragraph);
} 

只要数组不包含被视为布尔 false 的内容,这对所有集合和数组都有效。

如果您要迭代 childNode,您还可以使用firstChild 和nextSibling 属性。

var parentNode = document.getElementById('foo');
for (var child = parentNode.firstChild; child; child = child.nextSibling) {
  doSomething(child);
}

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).

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.

In cases where you are iterating over the childNodes you can also use the firstChild and nextSibling properties.

var parentNode = document.getElementById('foo');
for (var child = parentNode.firstChild; child; child = child.nextSibling) {
  doSomething(child);
}
神仙妹妹 2024-11-04 19:41:13

现在在 ES2015 中,您可以使用 Array.from 方法从任何类似数组的对象创建一个 Array 实例,因此这应该可以工作:

const divList = Array.from( document.getElementsByTagName("div") );

有关更多信息:https://developer.mozilla.org/en/docs/Web/ JavaScript/Reference/Global_Objects/Array/from

Now in ES2015 you can make use of Array.from method which creates an Array instance from any array-like object, so this should work :

const divList = Array.from( document.getElementsByTagName("div") );

For more information : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from

筱果果 2024-11-04 19:41:13

摘要:

NodeList 对象是一种表示节点集合的数据结构。 DOM 上下文中的节点可以是以下内容:

  1. 文档本身
  2. DOM 元素(即 HTML/SVG 元素)
  3. 文本
  4. 注释

NodeList 不是数组,而是数组NodeList 是一个可迭代数据结构,这意味着我们可以使用for..of 循环遍历值(即节点项)。此外,在 NodeList 原型上还有一些不错的实用函数,这使得使用它们更加方便。

例子:

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>

这是 Nodelist 在浏览器 (chrome) 开发工具中的样子:

在此处输入图像描述


您可以使用以下表示法访问 NodeList 的元素:

 myNodelist[0]; // grabs the first item of the NodeList

因为你只是使用一个键来对对象的属性值进行操作。在此示例中,属性的键是数字零,值是 DOM 元素。

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:

  1. The document itself
  2. DOM elements (i.e. HTML/SVG elements)
  3. Text
  4. comments

A NodeList is not an array, however a NodeList is an iterable data 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.

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:

enter image description here


You can access the elements of a NodeList with the following notation:

 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文