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

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>

If you're using ES6, you can use [...selectors] syntax, like this:

let getMappingList = function (list) {
  console.log(typeof list);

  for (let item of list) {
    console.log(item);
  }
  
  console.log("___________________");
  
  list.map(item => console.log(item));
};

getMappingList([...document.querySelectorAll("li")]);
<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>

After getting the list, we can also use map function, or looping the list using for...of... syntax.


Array(...selectors) is the same way to use:

let getMappingList = function (list) {
  console.log(typeof list);

  for (let item of list) {
    console.log(item);
  }
  
  console.log("___________________");
  
  list.map(item => console.log(item));
};

getMappingList(Array(...document.querySelectorAll("li")));
<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); })

Tags:

Javascript