NodeList object in javascript

ppoliani picture ppoliani · Mar 31, 2011 · Viewed 60.6k times · Source

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

Answer

brielov picture brielov · Aug 8, 2013

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