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
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]')]
[].forEach.call
paradigm critique here - toddmotto.com/ditch-the-array-foreach-call-nodelist-hack - offers better context. To show how it doesn't exactly work as explained, trying running [1, 2, 3].slice.call(nodeList)
and notice you get the same result. Try playing around with the number of entries in the original array, you still get the same result. –
Cabasset getElementsByClassName
returns an HTMLCollection, not a NodeList. This difference is important. https://mcmap.net/q/129581/-difference-between-htmlcollection-nodelists-and-arrays-of-objects –
Soult Array.from(nodeList).map(n => n.textContent)
is a one liner beauty, for example. –
Diactinic Array.from(nodeList)
or [...nodeList]
are both great tools. However, if you find yourself writing [...nodeList].forEach()
, then you can probably just iterate over the plain NodeList rather than spreading it out into an array. If you are worried about browser support, there is an extremely simple polyfill - if (window.NodeList && !NodeList.prototype.forEach) NodeList.prototype.forEach = Array.prototype.forEach
–
Cabasset 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];
}
forEach
works on type Array
, but not with bilbo.getElementsByTagName("taggins")
. –
Broom 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
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.
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);
});
Array.prototype.forEach.call(links, function() {})
;) –
Bummer [].slice.call
–
Tamie 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);
}
undefined
, null
, 0
etc.) values would... –
Bummer 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
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:
- The document itself
- DOM elements (i.e. HTML/SVG elements)
- Text
- 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.
© 2022 - 2024 — McMap. All rights reserved.
[].slice.call(nodeList)
works like a charm for me. I would love to know why/how it works. – Sunny