Javascript Filter Function - Trying to get it right

I need help finding out exactly how I should use the filter.

The following works fine:

let nums = [10, 12, 15, 20] nums.filter(num => num > 14) 

result = [15, 20]

If I understand this correctly, I pass a function with the argument num as an argument.

Now here where everything gets confusing (Keep in mind that I'm not an advanced js programmer)

I have an array of html elements

 let fields = document.getElementsByClassName("f-field") 

Each element of the returned array contains a bunch of other html elements, it looks something like this.

 <div class="f-field"> <textarea id="9008" name="Logo"></textarea> </div> 

Internal HTML can be textareas, selects, input, whatever ...

I tried this and he says

"fields.filter is not a function"

 fields.filter(field => field.getElementsByName("Logo")) 

I assume the filter does not work for an array of html elements. Or am I doing it wrong?

Thanks in advance, I'm trying to understand javascript

+5
source share
3 answers

DOM query methods, such as getElementsByClassName and querySelector , return collections that look like arrays but not arrays ( HTMLCollection , NodeList ). They have numbered keys that you can iterate over, and length properties too, but do not support array generators like filter , forEach or map .

You can apply an array object to an array using array = Array.from(source) . If you write ES6, you can also use the spread operator: array = [...source]

So you can write your code as follows:

 let fields = document.querySelectorAll('.f-field'); logos = Array.from(fields).filter(field => field.getElementsByName('logo')); 

And again, why bother filtering and moving all this when you can just pass the CSS selector directly to querySelectorAll ? eg.

 let logos = Array.from(document.querySelectorAll('.f-field [name="logo"]')); 
+6
source

Yes, it’s a little complicated. getElementsByClassName does NOT return an array. It returns an HTMLCollection , which behaves like an array in some way (you can iterate over it and have a length), but does not contain most of the array methods .

+4
source

You can convert to an array as follows

 var filteredFields = [...document.getElementsByClassName("f-field")].filter(item => itemTest(item)); 

Read more about the distribution operator in MDN

0
source

Source: https://habr.com/ru/post/1266653/


All Articles