The result of `document.getElementsByClassName` does not have array methods such as` map`, although 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 causes an error because it is mapnot defined, although tiles are an array. If I create such an array, then the map works just fine:

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

The workaround is to attach the map to these fragments:

tiles.map = Array.prototype.map;

It works great. My question is: why tilesdoes not it contain a card? Isn't that an array?

+4
source share
1 answer

That's right, this is not an array. It is massive.

Do not attach mapto tiles. Just do

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

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

. ,

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

.

, map , :

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

. MDN. NodeList, HTMLCollection, getElementsByClassName.

ES6 tiles ,

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

All Articles