Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use .map() in nodelist in javascript?

Tags:

javascript

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);
    })
like image 614
Shubham Kumar Avatar asked Nov 17 '18 09:11

Shubham Kumar


People also ask

Can you use map on a NodeList?

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.

Can I use map on HTMLCollection?

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.

How do I access NodeList elements?

const myNodeList = document. querySelectorAll("p"); The elements in the NodeList can be accessed by an index number.


2 Answers

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>
like image 185
Hassan Imam Avatar answered Sep 19 '22 15:09

Hassan Imam


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); })
like image 44
Shane Avatar answered Sep 21 '22 15:09

Shane