22

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.

ryandlf
  • 27,155
  • 37
  • 106
  • 162
  • 3
    As a note, an `HTMLCollection` (or indeed any array-like object) can be converted into a true array with `Array.prototype.slice.call(obj)`. – lonesomeday Oct 07 '12 at 15:37
  • 3
    @lonesomeday: Except for in IE8 and lower. :( – I Hate Lazy Oct 07 '12 at 15:38
  • 1
    ryandlf: You should reconsider the design of your `isArray` function so that you're not creating the `type` function every time `isArray` is invoked. That's quite an expensive operation compared to doing it once, and merely calling it. – I Hate Lazy Oct 07 '12 at 15:39
  • You should the native way to check whether it's an Array: `Array.isArray(youVariable)` – wle8300.com Jul 22 '16 at 17:35

2 Answers2

29

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.

I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • Understood, but in my situation, where I am checking for an array and if that check results in true, then I allow array like actions to be performed on the element. Would any functionality fail that would normally work on an array? – ryandlf Oct 07 '12 at 15:35
  • @ryandlf: Yes, it would fail. Please see my updated answer. They should be considered entirely different. To get Array behavior, you'd need to convert it to an Array first. – I Hate Lazy Oct 07 '12 at 15:37
  • When calling array methods with array-likes, why javascript doesn't convert it automatically like it does when `"2" + 2`? – ptkato Apr 08 '16 at 05:07
7

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.

Community
  • 1
  • 1
rdonatoiop
  • 1,185
  • 1
  • 14
  • 28