NodeList object in javascript

≡放荡痞女 提交于 2019-12-28 08:07:32

问题


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


回答1:


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]')]



回答2:


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



回答3:


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




回答4:


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



回答5:


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.




回答6:


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



回答7:


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




回答8:


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:


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.



来源:https://stackoverflow.com/questions/5501433/nodelist-object-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!