How to use the map method on NodeList like we do on Array

On an array, we can call map to easily get another array with manipulated items. Here's an example:

const arrayDemo = ['foo', 'bar']
console.log(arrayDemo.map(item => item.toUpperCase()))  // ['FOO', 'BAR']

But we often meet array like objects like NodeList which are returned by dom methods like querySelectorAll. On NodeList, we cannot use map directly, but we have a similar choice.

Use Array.from to simulate map

const tags = Array.from(data.querySelectorAll('.tag'), (e) => {
    return e.innerText.trim()
})

data.querySelectorAll('.tag') returns a NodeList object, we use Array.from to manipulate each node and collect them to the result array tags.

Posted on 2023-09-01