Categories
JavaScript Answers

How to Filter or Map Nodelists with JavaScript?

Spread the love

Sometimes, we want to filter or map nodelists with JavaScript.

In this article, we’ll look at how to filter or map nodelists with JavaScript.

Filter or Map Nodelists with JavaScript

To filter or map nodelists with JavaScript, we can use the spread operator to convert the nodelist to an array.

For instance, if we have the following HTML:

<p>
  foo
</p>
<p>
  bar
</p>

Then we can convert the nodelist with the selected p elements and call map and filter on it by writing:

const nodes = document.querySelectorAll('p')
const texts = [...nodes].map(n => n.textContent)
console.log(texts)
const filtered = [...nodes].filter(n => n.textContent.includes('foo'))
console.log(filtered)

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.

And then we call map to map the node array to an array of text.

Then we call filter on the array of nodes with a callback to return the nodes with textContent that includes 'foo' .

Therefore, texts is [“n foon”, “n barn”]

And filtered has an array with the first p element.

Conclusion

To filter or map nodelists with JavaScript, we can use the spread operator to convert the nodelist to an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *