Why am i getting this error? How can i access and print the nodes when i'm selecting the <li>
tags with querySelectorAll
?
script.js:14 Uncaught TypeError: list.map is not a function
HTML
<ul class="wrapper1" id="testDiv">
<li class="cake">Carrots</li>
<li class="cake">Cake</li>
<li class="cake">Wheat</li>
<li class="cake">Balloons</li>
</ul>
JS
let list = document.querySelectorAll("li");
let items = list.map(elem => {
console.log(elem);
})
To filter or map nodelists with JavaScript, we can use the spread operator to convert the nodelist to an array. We call document. querySelectorAll to return a nodelist with the p elements. Then we use the spread operator to spread the items in the nodes nodelist into an array.
Even though map() is a function of Array. prototype, it works on any array-like iterable. We just need a way to call it on our HTMLCollection . Because elements is not an array, it doesn't have the methods in Array.
const myNodeList = document. querySelectorAll("p"); The elements in the NodeList can be accessed by an index number.
querySelectorAll()
returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors. Use array#from
to convert NodeList to array then iterate through array#map
.
let list = document.querySelectorAll("li");
let items = Array.from(list).map(elem => {
console.log(elem);
})
<ul class="wrapper1" id="testDiv">
<li class="cake">Carrots</li>
<li class="cake">Cake</li>
<li class="cake">Wheat</li>
<li class="cake">Balloons</li>
</ul>
In addition to Itang and Foo's suggestion, you can also use:
[].concat(document.querySelectorAll("li")).map((el) => { console.log(el); })
In fairness I think Foo's suggestion using spread syntax Is probably the most elegant, I'm just not sure how widely the spread operator is supported for NodeLists. (pasted below for reference)
[...document.querySelectorAll('li')].map((el) => { console.log(el); })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With