I understand that HTMLCollection is not actually an array, or else it would be defined as an array. I use a help function that I call isArray() to detect whether or not an object is an array. I use this little helper all over the place and i've been running problems on this returning false when checking against an htmlCollection.
var isArray: function(obj) {
var type = Function.prototype.call.bind( Object.prototype.toString );
return type(obj) === '[object Array]' || type(obj) === '[object HTMLCollection]';
}
Would it be wrong to check for the htmlCollection type within this helper function and assume that it is the same thing as an array? What makes it any different? Other than its html elements as opposed to javascript objects.
One way to convert an HTMLCollection to a JavaScript array is to use the slice method. We get divs by call querySelector to select all the divs in the HTML. We just call slice with divs and it'll return the div element objects in an array. We call slice on an empty array and pass in the divs HTML.
An HTMLCollection object is an array-like list (collection) of HTML elements.
The Array. from() method is used to create a new Array from an array-like or iterable object. The HTMLCollection is passed to this method to convert it into an Array. The forEach() method can now be used to iterate over the elements like an array and display them.
No, it's an HTMLCollection
, not an Array
.
It has Array-like characteristics, like numeric properties, and a .length
property, but it does not inherit from Array.prototype
. Therefore it does not have the standard Array
methods, and so should be seen as being different.
Another significant difference is that HTMLCollection
is a "live" collection, which means that it updates as the DOM updates. If you remove one of its nodes from the DOM, it will be removed from the HTMLCollection
automatically.
If you are considering an Array conversion, please refer to this post:
Most efficient way to convert an HTMLCollection to an Array.
They discussed some methods, and the solution in the selected answer also worked in a situation I´ve experienced.
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