How do I filter elements from NodeList returned by querySelectorAll()?
Answers:
When you use
document.querySelectorAll(), it returns aNodeList, which is a collection of elements that match the specified selector. While aNodeListbehaves like an array in some contexts, it doesn't have all the array methods. To filter elements from aNodeList, you can convert it into an actual array and then useArray.prototype.filter().Here's how you can do it:
Using
Array.from()You can convert the
NodeListinto an array usingArray.from()and then apply thefiltermethod:const nodeList = document.querySelectorAll('your-selector'); const filteredElements = Array.from(nodeList).filter(element => { // Your filtering condition return element.classList.contains('your-class'); // Example condition });Using the Spread Operator
Another way to convert the
NodeListto an array is to use the spread operator (...):const nodeList = document.querySelectorAll('your-selector'); const filteredElements = [...nodeList].filter(element => { // Your filtering condition return element.classList.contains('your-class'); // Example condition });Example
Here's a complete example demonstrating how to filter elements based on a condition:
<div class="item"></div> <div class="item special"></div> <div class="item"></div> <div class="item special"></div> <script> const nodeList = document.querySelectorAll('.item'); const filteredElements = Array.from(nodeList).filter(element => { return element.classList.contains('special'); }); console.log(filteredElements); // This will contain only the elements with the class 'special' </script>Summary
In summary, to filter elements from a
NodeList:- Convert the
NodeListinto an array using eitherArray.from()or the spread operator. - Use the
filter()method with your filtering condition to get the desired elements.
- Convert the