Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
28
rated 0 times [  34] [ 6]  / answers: 1 / hits: 73091  / 9 Years ago, tue, july 28, 2015, 12:00:00

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?


More From » arrays

 Answers
18

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]

[#65646] Sunday, July 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susand

Total Points: 690
Total Questions: 101
Total Answers: 104

Location: Lesotho
Member since Wed, Jun 2, 2021
3 Years ago
;