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);
source to share
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
source to share
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'));
source to share