Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeList object in javascript

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

like image 443
ppoliani Avatar asked Mar 31 '11 14:03

ppoliani


People also ask

Is NodeList same as an array?

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 NodeList and HTMLCollection?

What is the difference between a HTMLCollection and a NodeList? A HTMLCollection contains only element nodes (tags) and a NodeList contains all nodes.

What is a NodeList explain a live NodeList and a static NodeList?

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.


1 Answers

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]')] 
like image 84
brielov Avatar answered Sep 22 '22 00:09

brielov