Im attempting to return an array of my list items if they contain the text "Flexbox" in them.
Im 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);
The "filter is not a function" error occurs when we call the filter() method on a value that is not of type array. To solve the error, convert the value to an array before calling the filter method or make sure to only call the method on arrays. Here is an example of how the error occurs. Copied!
Unfortunately, JavaScript objects don't have a filter() function. But that doesn't mean you can't use filter() to filter objects, you just need to be able to iterate over an object and convert the object into an array using Object. entries() .
querySelectorAll returns a NodeList not an Array. You can convert it to an Array if you'd like to use Array methods.
var items = document.querySelectorAll('li');
var itemsArray = Array.from(items);
The querySelectorAll
does not return an array
, that is the reason why filter
is not defined (which is a function of array
). In this case, you should call filter
function from Array.prototype
and use textContent.indexOf(string)
to check if the element has the text content you want (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 the sample here: https://jsbin.com/hibixipoyo/edit?html,js,output
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With