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

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?

Answers:

Answer

Right, it's not really an array. It's an "array-like".

Don't attach map to tiles. Just do

Array.prototype.map.call(tiles, function...)

Some might suggest

Array.prototype.slice.call(tiles).map(function...

which sort of boils down to the same thing. There are those who prefer to write

[].slice.call(tiles).map(function...

which saves a few keystrokes.

Of course, since you're not really using map to return an array, you could loop in the old-fashioned way:

for (var i = 0; i < tiles.length; i++) {
    tiles[i].addEventListener("click", function(e){
        console.log("click!");
    });
}

See also explanation at MDN. Although this discusses NodeList, the same principles apply to HTMLCollection, which is what getElementsByClassName returns.

In ES6, we have some easier ways to turn tiles into an array, including

[...tiles]
Array.from(tiles)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.