Saturday, May 9, 2015

JavaScript: Transfrom Nodelist into Array

We can get DOM nodelist from querySelectorAll or getElementsByTagName or getElementsByClassName (new) method. The nodelist can't be "fully" processed like an array can.
We can loop through (read, and maybe set/write) the elements (using any of loop block methods), but there are methods which won't work for this object (it will return error code).

Here's the basic idea
We need to create an empty array, then put the elements from the nodelist (array-like) to the (actual) empty array.
The newly created array will then be available for any of JavaScript array methods.

JavaScript snippet
Updated May 14, 2015


Snippet usage
There's a shorter way to do that using Array.prototype.slice.call(the_nodelist) as you may stumble on neat jQuery library.
More documentation of Array.prototype.slice.call(the_nodelist) at MDN

For example
Added May 14, 2015
The same usage as the first snippet.

No comments:

Post a Comment

Tell me what you think...