Filter not a function?

I am trying to return an array of list items if they contain the text "flexbox" in them.

I'm getting this error: Uncaught TypeError: items.filter is not a function

    <ul>
        <li data-time="5:10">Flexbox 1</li>
        <li data-time="5:10">Something else</li>
        <li data-time="5:40">Flexbox 2</li>
        <li data-time="5:10">Something also else</li>
        <li data-time="5:40">More Flexbox for you</li>
    </ul>


'use strict';

var items = document.querySelectorAll('li');

var itemsFlex = items.filter(function(item) {
    return item.includes('Flexbox')
});

console.log(itemsFlex);

      

+4


source to share


4 answers


querySelectorAll returns NodeList not Array . You can convert it to an array if you want to use the Array methods.



var items = document.querySelectorAll('li');
var itemsArray = Array.from(items);

      

+12


source


querySelectorAll

does not return array

, so filter

it is undefined (which is a function array

). In this case, you have to call the function filter

from Array.prototype

and use textContent.indexOf(string)

to check if the element has text content ( Flexbox

). For sample:

var items = document.querySelectorAll('li');
var filter   = Array.prototype.filter;

var itemsFlex = filter.call(items, function(item) {
    return item.textContent.indexOf('Flexbox') >= 0;
});

console.log(itemsFlex);

      



See a sample here:    https://jsbin.com/hibixipoyo/edit?html,js,output

+2


source


The reason is that querySelectorAll does not return an array.

You can convert NodeList to array with:

var itemsArray = Array.prototype.slice.call(document.querySelectorAll("li"));

      

Source: https://davidwalsh.name/nodelist-array

+1


source


document.querySelectorAll()

returns a NodeList

. NodeLists

are massive, but do not contain many of the methods provided Array

for, for example, Each, map, filter, etc. If you want to use these functions, you must convert the NodeList to an array:

var nodesArray = [].slice.call(document.querySelectorAll('li'));

      

0


source







All Articles