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
allImgs = Array.from(allImgs);
stackoverflow.com/questions/222841/…
@ Flawyte Eek, it's not working for me yet. I'm probably overlooking something super basic. Here's what I got:
window.onload = function(){ var allImgs = document.getElementsByClassName("pft"); var newImgs = [].slice.call(allImgs); console.log(newImgs.typeof); newImgs.map( function(arrayCell){ return arrayCell.addEventListener("mouseover, flipOver"); } ); };
@Flawyte sorry, the console log in the comment above just shows as "undefined". It doesn't seem to turn into an array?
@Flawyte Aaagh I found it myself sorry; I borked the addEventListener parenthesis contents (wrong quotation marks). Thanks!
@Flawyte Modern browsers support
Array.from
which is cleaner thanArray.prototype.slice.call
.