Categories
arrays javascript

Javascript .map() is not a function

I am new here (and new to JavaScript), so please excuse my super basic questions.
I have a HTML page with different images that all share a class on it. By using getElementsByClassName, I get an array. I want to add an event listener to each of the cells in the array by using the .map() function.

This is what I have:

window.onload = function(){
var allImgs = document.getElementsByClassName("pft");
var newImgs = allImgs.map(
function(arrayCell){
return arrayCell.addEventListener("mouseover, functionName");
}
);
};

This keeps showing the error “allImgs.map is not a function” even when I change the inner function to something that doesn’t include the event listener.

I have another version of this code where I just loop through the array cells within window.onload and add the event listener to each of them that way and it works.
Why isn’t the .map() function working? Can it not be used in window.onload?

getElementsByClassName() returns an HTMLCollection not an Array. You have to convert it into a JavaScript array first :

allImgs = Array.prototype.slice.call(allImgs);
// or
allImgs = [].slice.call(allImgs);
// or (thanks @athari)
allImgs = Array.from(allImgs);
// or (thanks @eliaz-bobadilla)
allImgs = [...allImgs]