Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a DOM node list to an array in Javascript?

I have a Javascript function that accepts a list of HTML nodes, but it expects a Javascript array (it runs some Array methods on that) and I want to feed it the output of Document.getElementsByTagName that returns a DOM node list.

Initially I thought of using something simple like:

Array.prototype.slice.call(list,0) 

And that works fine in all browsers, except of course Internet Explorer which returns the error "JScript object expected", as apparently the DOM node list returned by Document.getElement* methods is not a JScript object enough to be the target of a function call.

Caveats: I don't mind writing Internet Explorer specific code, but I'm not allowed to use any Javascript libraries such as JQuery because I'm writing a widget to be embedded into 3rd party web site, and I cannot load external libraries that will create conflict for the clients.

My last ditch effort is to iterate over the DOM node list and create an array myself, but is there a nicer way to do that?

like image 295
Guss Avatar asked Apr 29 '10 05:04

Guss


People also ask

Is NodeList an array?

Note: Although NodeList is not an Array , it is possible to iterate over it with forEach() . It can also be converted to a real Array using Array. from() .

How do I turn querySelectorAll into an array?

You can convert it to an array by using the slice method from the Array prototype: var elList = document. querySelectorAll('. viewcount'); elList = Array.

Which function returns the DOM node list?

The HTML DOM NodeList Object All browsers return a NodeList object for the property childNodes . Most browsers return a NodeList object for the method querySelectorAll() .

How do you convert a list of objects into an object?

The quickest way to convert an array of objects to a single object with all key-value pairs is by using the Object. assign() method along with spread operator syntax ( ... ). The Object.


1 Answers

In es6 you can just use as follows:

  • Spread operator

     var elements = [... nodelist] 
  • Using Array.from

     var elements = Array.from(nodelist) 

more reference at https://developer.mozilla.org/en-US/docs/Web/API/NodeList

like image 99
camiloazula Avatar answered Sep 27 '22 19:09

camiloazula