Skip to content

Instantly share code, notes, and snippets.

@Anthodpnt
Last active December 13, 2016 16:09
Show Gist options
  • Save Anthodpnt/508bdb046f0983e9ec3c6528f87343b5 to your computer and use it in GitHub Desktop.
Save Anthodpnt/508bdb046f0983e9ec3c6528f87343b5 to your computer and use it in GitHub Desktop.
Conversion - NodeList to Array
/**
* This gist is for Javascript beginners.
* @author: Anthony Du Pont <[email protected]>
* @site: https://www.twitter.com/JsGists
*
* Methods like `querySelectorAll()` are handy to select multiple DOM elements at once.
* But these methods return a `NodeList` which is a list of all the matching DOM elements.
* No problem at first glance but when you dig a little bit you'll notice there are some
* issues when you want to manipulate them.
*
* Example:
* I want to select all my list items and from all of the matching DOM elements I want to
* extract the last one and store it in a variable calles `item`. This example is not
* really useful but it will do the job to explain the problem.
**/
// Bad
const nodeList = document.querySelectorAll('li'); // Get a `NodeList` of `<li>`
const item = nodeList.pop(); // Throw an error because `pop()` doesn't exist for `NodeList`
// Good
const nodeList = document.querySelectorAll('li'); // Get a `NodeList` of `<li>`
const array = Array.prototype.slice.call(nodeList); // `NodeList` to `Array`
const item = array.pop(); // Return the last element matched as expected
@Spharian
Copy link

Spharian commented Dec 7, 2016

Another alternative: [...document.querySelectorAll('li')].pop()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment