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 may look like an array, but in reality, they both are two completely different things. A NodeList object is basically a collection of DOM nodes extracted from the HTML document. An array is a special data-type in JavaScript, that can store a collection of arbitrary elements.
What is the difference between a HTMLCollection and a NodeList? A HTMLCollection contains only element nodes (tags) and a NodeList contains all nodes.
A NodeList object is a collection of nodes... 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.
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]')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With