Danya Lette

JS's HTMLCollection is a Pseudo-Array


var realArray = Array.prototype.slice.call(document.getElementsByClassName('classname'), 0);

Or, if you want to get cute about it (which i always do)

var realArray = [].slice.call(document.getElementsByClassName('classname'), 0);

The class selectors for javascript’s dom api – getElementsByClass and getElementsByClassName – don’t return arrays but rather pseudo-arrays called HTMLCollections. This came as a surprise to me after I started switching from using jquery to using pure js.

An HTMLCollection has some methods associated with it, and you can still grab a handler to your desired element via index, i.e. you can

var myElement = document.getElementsByClassName('classname')[1];

but there are lots of super handy array methods you might wanna access. i use ‘forEach’ a fair bit so i always convert my HTMLCollections to a true array.

note: IE pre-9 doesn’t support forEach. but you can manually add the method to the array constructor:</p>

// from stackoverflow user Kishor Subedi:
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(fn, scope) {
        for(var i = 0, len = this.length; i &lt; len; ++i) {
            fn.call(scope, this[i], i, this);