Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result of `document.getElementsByClassName` doesn't have array methods like `map` defined, even though it is an array

Tags:

I have the following bit of code to select some divs and add a click handler on them

var tiles = document.getElementsByClassName("tile");

tiles.map(function(tile, i){
    tile.addEventListener("click", function(e){
        console.log("click!");
    });
});

This throws an error because map is not defined, even though tiles is an array. If I make an array like this, then map works fine:

var a = [1, 2, 3, 4];
a.map(/*whatever*/);

A workaround is to attach map to tiles like this:

tiles.map = Array.prototype.map;

This works fine. My question is why doesn't tiles have map defined on it? Is it not really an array?


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!