Reputation: 339
Why the following code doesn't work (alert is not executed)? custom_table
is some file upload fields in html, its length is 10.
var custom_table=document.getElementsByName('custom_table');
var result = custom_table.filter( function (x) { return x.value });
alert(result.length);
If I replace custom_table
with names
in the following code, it works fine.
var names = new Array();
var object = { name : "Joe", value:20, email: "[email protected]"};
names.push(object);
object = { name : "Mike", value:50, email: "[email protected]"};
names.push(object);
object = { name : "Joe", value:45, email: "[email protected]"};
names.push(object);
Thanks.
Upvotes: 2
Views: 2210
Reputation: 62027
getElementsByName
returns an HTMLCollection
*, which is not an array. filter()
is only on arrays. You can dump it into an array easily enough:
var elementCollection = document.getElementsByName('myname');
var elementArray = Array.prototype.slice.call(elementCollection, 0);
elementArray.filter(...); // this will now work
*or a NodeList
, depending on the browser, the distinction isn't very important though
Upvotes: 3
Reputation: 413720
The return value from getElementsByName
is not a JavaScript array. You can copy the contents into one, however:
var custom_table=document.getElementsByName('custom_table');
custom_table = [].slice.call(custom_table, 0);
Then .filter
, .map
, etc. will work.
Upvotes: 3