Is it possible to filter elements selected by querySelectorAll() using an array method?
Answers:
Yes, you can filter elements selected by
querySelectorAll()using an array method. However, sincequerySelectorAll()returns aNodeList, which is not an array, you'll first need to convert thisNodeListinto an array. You can do this usingArray.from()or the spread operator (...). Once you have an array, you can use array methods likefilter().Here’s an example using
Array.from():// Select all elements with the class "item" const items = document.querySelectorAll('.item'); // Convert NodeList to an array and filter it const filteredItems = Array.from(items).filter(item => { // Your filter condition here, for example: return item.textContent.includes('specific text'); }); // Now, filteredItems is an array of elements that meet your criteria console.log(filteredItems);Alternatively, you can use the spread operator:
// Select all elements with the class "item" const items = document.querySelectorAll('.item'); // Convert NodeList to an array using the spread operator and filter it const filteredItems = [...items].filter(item => { // Your filter condition here return item.textContent.includes('specific text'); }); // Now, filteredItems is an array of elements that meet your criteria console.log(filteredItems);Both methods effectively allow you to convert the
NodeListto an array so that you can use array methods likefilter().