Last active
December 13, 2016 16:09
-
-
Save Anthodpnt/508bdb046f0983e9ec3c6528f87343b5 to your computer and use it in GitHub Desktop.
Conversion - NodeList to Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another alternative:
[...document.querySelectorAll('li')].pop()