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");, i){
    tile.addEventListener("click", function(e){

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];*whatever*/);

A workaround is to attach map to tiles like this: =;

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



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

Don't attach map to tiles. Just do, function...)

Some might suggest

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


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){

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



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.