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



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

i have next bit of code select divs , add together click handler on them

var tiles = document.getelementsbyclassname("tile"); tiles.map(function(tile, i){ tile.addeventlistener("click", function(e){ console.log("click!"); }); });

this throws error because map not defined, though tiles array. if create array this, map works fine:

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

a workaround attach map tiles this:

tiles.map = array.prototype.map;

this works fine. question why doesn't tiles have map defined on it? not array?

right, it's not array. it's "array-like".

don't attach map tiles. do

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

some might suggest

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

which sort of boils downwards same thing. there prefer write

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

which saves few keystrokes.

of course, since you're not using map homecoming array, loop in old-fashioned way:

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

see explanation @ mdn. although discusses nodelist, same principles apply htmlcollection, getelementsbyclassname returns.

javascript arrays map

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -