The functionality of .map() in Javascript is non-existent

I am completely new to this community (and JavaScript is also new for me), so I apologize in advance for asking some very basic questions. I have an HTML page with various images, all of which share a common class. After using getElementsByClassName, I obtain an array. My goal is to attach an event listener to each cell in the array by utilizing the .map() function.

Here is my current attempt:

window.onload = function(){
var allImgs = document.getElementsByClassName("pft");

var newImgs = allImgs.map(
        function(arrayCell){
            return arrayCell.addEventListener("mouseover, functionName");
        }
    );
}; 

Unfortunately, I keep receiving the error "allImgs.map is not a function" even when I modify the inner function to remove the event listener.

In another version of this code, I simply loop through the array cells within window.onload and add the event listener to each one, which works perfectly fine. So, why isn't the .map() function working here? Is it possible that it cannot be used within window.onload?

Answer №1

getElementsByClassName() does not return an Array, but rather an HTMLCollection. To work with it as an array in JavaScript, you will need to convert it using one of the following methods:

convertedArr = Array.prototype.slice.call(originalArr);

// alternatively
convertedArr = [].slice.call(originalArr);

// or (credit to @john-doe)
convertedArr = Array.from(originalArr);

// or (credit to @jane-smith)
convertedArr = [...originalArr]

Answer №2

Whenever I use getElementsByClassName, it returns an array-like object.

No, that's not exactly correct.

It actually returns a live HTMLCollection, which behaves like an array but is not technically an array.

Despite this distinction, you can still utilize methods like map on the HTMLCollection as if it were a real array.

    var text_content = [].map.call(
      document.getElementsByClassName("sdf"),
      function (currentValue, index, collection) {
        return currentValue.innerHTML;
      }
    );
    console.log(text_content);
  <p class="sdf">foo</p>
  <p class="sdf"></p>
  <p class="sdf">bar</p>
  <p class="sdf"></p>
  <p class="sdf"></p>
          

Answer №3

If you prefer, you can utilize the map method like this:

[].map.call(allImages, function() { ... });

Although, in this case, it is recommended to use Array.prototype.forEach for better efficiency.

Answer №4

Easy way to shorten the syntax:

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

Answer №5

const elements = document.querySelectorAll('.demo');
for(let i = 0; i < elements.length; i++) {
  let element = elements[i];
  element.onmouseleave = function() {
    this.style.color = "#000";
  }
  element.onmouseover = function() {
    this.style.color = 'red';
  }

}
.demo {
  cursor:pointer;
}
<div>
  <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>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Organizing files and folders based on their size within the Document Directory in a Swift iOS application

My goal is to organize my files and folders in the document directory based on their Size. I managed to sort them by Date using URLResourceKey and properties, but I encountered a problem when trying to do the same for Size. The issue arises because the Si ...

React Native - Invariant Violation: Objects cannot be used as a React Child (Utilizing Node.js for the backend)

Trying to calculate the total sum of orders and their quantity using Node JS on the backend. However, encountering issues with the fetch functions not working properly or missing something unknown. The API works as expected when tested in Postman, but err ...

Utilizing tag keys for inserting text and adjusting text sizes within a Web application

Creating an online editing interface for coursework where keyboard events are used. The goal is to have the tab key insert text, while also reducing the size of the text on that line. However, upon using getElementById, an error message pops up stating: ...

Implementing the insertion of data using array pointers

I am currently working on a program that adds records to a basic phone book. The code I have written so far seems to have an issue - the function stops and gets stuck at declaring struct record x, causing my added record not to display properly and ultimat ...

Issue with Bing Maps Infobox mouseout event: Problem arises when attempting to change the htmlContent asynchronously

Can anyone provide assistance? I am currently utilizing the latest Bing Maps version (v8), and I have encountered an issue. When creating a custom Infobox and populating its contents using an async request such as setTimeout/ajax, the mouseout event is tr ...

What exactly is the purpose of utilizing node js and can someone explain to me what constitutes a

After mastering HTML and CSS, I've started diving into JavaScript. However, I'm curious about Node.js. What exactly is it, why do I need it, and can you explain what a framework is in general? Sorry if these questions sound silly! ...

Making a single variable object as opposed to using multiple variables

In order to improve the code structure, I am looking to consolidate all properties into a JavaScript object instead of using multiple variables: // Method 1 // This method gives an error as _inp cannot be accessed by input_value // Uncaught TypeError: Can ...

Discover the process for breaking down JSON data into separate stages using the Express API

My API architecture is causing a problem as I try to insert it into an array called items[]. https://i.stack.imgur.com/qe802.png The setup involves a simple API built on express + mongodb. The challenge lies in figuring out how to store data from the pos ...

Express.js's Handlebars failing to render elements from an array

I am currently developing an Express.js application that utilizes Handlebars for templating. One of the routes in my application fetches station data from MongoDB using Mongoose and then passes it to a Handlebars template. Although most of the data is bein ...

Does anyone know if it's feasible to return a value from PHP to an HTML form without relying on JavaScript?

Currently, I am in the process of learning how to create a basic web form. My goal is to develop an HTML web form that sends a number to PHP and then displays the number in another text field without refreshing the page. After doing some research online, ...

During the build process, Next.js encounters difficulty loading dynamic pages

My Next.js application is utilizing dynamic routes. While the dynamic routes function properly in development mode, I encounter a 404 error when deploying the built app to Netlify. https://i.stack.imgur.com/45NS3.png Here is my current code setup: In _ ...

Tips on enclosing <li> elements within <ul> tags

Whenever I trigger the button within the .items class, it generates <li> elements in the following manner: <ul class="items"> <ul class="items"> <li>img1</li> ...

Issue with sizing and panning when using a combination of Three.js and CSS3Renderer

This issue is specific to Chrome. Here's what I have experimented with: I am utilizing the webGL renderer to position a plane geometry in a 3D environment using threejs. This particular code is running within a class, with the scene as one of its me ...

Having difficulties transmitting numerical values through res.send() in express with node

Currently, I'm faced with a challenge in my express application on node.js as I attempt to retrieve the "imdb rating." movies.json [{ "id": "3962210", "order": [4.361276149749756, 1988], "fields": { "year": 2015, "title": "David and Goliath" ...

The object literal's property 'children' is assumed to have a type of 'any[]' by default

Is there a way to assign the property myOtherKey with any value? I encountered a Typescript error that says.. A problem occurred while initializing an object. The property 'children' in the object literal implicitly has an array type of 'a ...

Click the link to find the JSON node that corresponds to the onclick event

After parsing JSON, the JS code below is returning a list of movie titles for me. Each movie title node contains additional attributes and values that are not currently being displayed. My goal is to have the other values in that specific node displayed wh ...

What is the best way to showcase the content from multiple uploaded files?

Below is an example demonstrating how to display the contents of a single uploaded file. .js $scope.uploadFilename = function (files) { if (!files[0]) { return; } var reader = new FileReader(); reader ...

Saving the author of a message from one function and transferring it to another

I'm currently working on a Discord bot that manages tickets as applications. I've almost completed it, but I want the bot to log the closed ticket when the -close command is used. I've experimented with different approaches, such as using a ...

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...

What strategies can I implement to prevent the JavaScript CallStack from becoming overloaded?

The code snippet below outlines the functionality achieved through JavaScript (specifically for a node.js COMET application): A request is sent to the server and held until there is a response. Upon receiving a response, the data is processed, and anothe ...