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 =
            return arrayCell.addEventListener("mouseover, functionName");

This keeps showing the error " 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 =;
// or
allImgs = [];
// or
allImgs = Array.from(allImgs);

By using getElementsByClassName, I get an array.

No, you don't.

You get a live HTMLCollection. This is array-like but is not an array.

Since it is sufficiently array-like, you can apply the map method from a real array.

    var text_content = []
      function (currentValue, index, collection) {
        return currentValue.innerHTML;
  <p class="sdf">foo</p>
  <p class="sdf"></p>
  <p class="sdf">bar</p>
  <p class="sdf"></p>
  <p class="sdf"></p>


Another option would be to use map directly:

[], function() { ... });

However, what you are doing is better achieved with Array.prototype.forEach.


Compact syntax:

[...document.getElementsByClassName("pft")].map(arrayCell => arrayCell.addEventListener("mouseover", "functionName"))

var elms = document.querySelectorAll('.demo');
for(var i = 0; i < elms.length; i++) {
  var elm = elms[i];
  elm.onmouseleave = function() { = "#000";
  elm.onmouseover = function() { = 'red';
.demo {
  <p class="demo">paragraph one</p>
  <p class="demo">paragraph two</p>
  <p class="demo">paragraph three</p>
  <p class="demo">paragraph four</p>
  <p class="demo">paragraph five</p>
  <p class="demo">paragraph six</p>


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.