I want to store the value of a specific element by its ID in an array using JavaScript

It is clear that there is a lot of repetitive code below...

var card0 = document.getElementById('c0');
var card1 = document.getElementById('c1');
var card2 = document.getElementById('c2');
var card3 = document.getElementById('c3');

var card4 = document.getElementById('c4');
var card5 = document.getElementById('c5');
var card6 = document.getElementById('c6');
var card7 = document.getElementById('c7');

var card8 = document.getElementById('c8');
var card9 = document.getElementById('c9');
var card10 = document.getElementById('c10');
var card11 = document.getElementById('c11');

card0.addEventListener("click", function() {revealCard(0); });
card1.addEventListener("click", function() {revealCard(1); });
card2.addEventListener("click", function() {revealCard(2); });
card3.addEventListener("click", function() {revealCard(3); });

card4.addEventListener("click", function() {revealCard(4); });
card5.addEventListener("click", function() {revealCard(5); });
card6.addEventListener("click", function() {revealCard(6); });
card7.addEventListener("click", function() {revealCard(7); });

card8.addEventListener("click", function() {revealCard(8); });
card9.addEventListener("click", function() {revealCard(9); });
card10.addEventListener("click", function() {revealCard(10); });
card11.addEventListener("click", function() {revealCard(11); });

Looking to optimize this code, I attempted to use a for loop:

var cards = [];
for(i=0; i<12; i++)
{
    cards[i] = document.getElementById('c'+i);
    cards[i].addEventListener("click", function() {revealCard(i); });
}

Unfortunately, the optimized version did not work as expected. Despite no errors being shown in the console, the functionality does not seem to be working correctly. Any suggestions or help would be greatly appreciated.

Answer №1

A better approach would involve assigning a class to the common parent of those elements and using addEventListener on it. By utilizing event bubbling, you can capture click events and respond accordingly based on the specific element.

For instance,

const wrapper = document.querySelector('.wrapper');

wrapper.addEventListener('click', event => {
  console.log(event.target.id)
})
<div class="wrapper">
  <button class="some-button" id="c0">
    c0
  </button>
  <button class="some-button" id="c1">
    c1
  </button>
  <button class="some-button" id="c2">
    c2
  </button>
</div>

Fiddle: https://jsfiddle.net/tkore/y9dmkco2/

Answer №2

The issue was caused by not declaring the i variable, consider using let

var c = [];
for (let i = 0; i < 3; i++) {
  c[i] = document.getElementById('c' + i);
  c[i].addEventListener("click", function() {
    console.log(i);
  });
}
<div id="c0">test</div>
<div id="c1">test</div>
<div id="c2">test</div>

Answer №3

To apply the code and integrate it in this manner, you can follow these steps -

const elements = {};
for(let index=0; index<12; index++)
{
    elements[`card${index}`] = document.getElementById(`card${index}`);
    elements[`card${index}`].addEventListener("click", function() {showCard(index); });
}

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

Preventing JQuery from interrupting asynchronous initialization

I am currently developing an AngularJS service for a SignalR hub. Below is the factory code for my service: .factory('gameManager', [function () { $.connection.hub.start(); var manager = $.connection.gameManager; return ...

What is the method for locating an element within an array?

The content being returned is presenting a challenge. How can I retrieve data from inside 0? I attempted to access it using date[0] without success const { data } = getData(); The result of console.log(data) is shown below: enter image description here ...

What is the reason that *(str+i) = *(str +j) is ineffective in this scenario?

void reverseString(char *str){ int i, j; char temp; for(i = 0, j = strlen(str) - 1; i < j; i++, j--){ temp = *(str + i); *(str + i) = *(str + j); *(str + j) = temp; printf("%c", *(str + j)); } } int mai ...

Is it possible to refactor this forwardRef so that it can be easily reused in a function?

Currently, I am in the process of transitioning my application to Material UI V4 and facing challenges with moving my react router Link components into forwardRef wrapped components when setting the 'to' prop programmatically. The code below doe ...

Resizing a profile image using Node.js

Allowing users on my website to crop an image for their profile picture is a priority. The cropped image should then be stored in an uploads folder on the server. Initially, I implemented this feature using PHP and the JCrop plugin. However, I am now tran ...

What steps should I take to transform [“link”, “395868”] into [title: “link”, content: “395868”]?

As a newcomer to javascript, I am finding it challenging to articulate my issue due to lack of adequate vocabulary. My current project involves building a chart with d3 and here is the data I require : data=[ ...

Place an overlay element in the top-left corner of a perfectly centered image

Currently, there is an image that is centered on the screen using flexbox: .center-flex { display: flex; justify-content: center; } <div class="center-flex"> <img id="revealImage"> </div> An attempt is be ...

Dealing with Typescript and React: The Frustration of Property Not Found on Interface, even though it clearly

Dealing with an API where I've linked the properties to an interface using an automated tool: export interface Root { stationId: number; results: Results; } To keep it concise, I'm skipping the additional results interfaces. I then make a fe ...

Upon clicking the "show more information" button on the page, JavaScript executes the function to display additional details

<a href="#" class="button">Read More</a><br> I'm currently struggling with programming a button on my website. Specifically, I need the Read More button to display all information related to the CDs I have for sale when clicked. A ...

Calculate the UV coordinates for a trio of CSG meshes

During a university project, I created a ThreeCSG subtraction in ThreeJS. The challenge I am facing now is applying a texture to this mesh due to the missing UV coordinates after processing. The project requirement mandates that it must be a ThreeCSG objec ...

The current error message states that the function is undefined, indicating that the Bookshelf.js model function is not being acknowledged

I have implemented a user registration API endpoint using NodeJS, ExpressJS, and Bookshelf.js. However, I encountered an error while POSTing to the register URL related to one of the functions in the User model. Here is the code snippet from routes/index. ...

What is the best way to transfer the JWT token from the server to the client using an HTTP header?

I have been searching for an answer on how to pass the JWT Token from the client to the server securely, but I am not satisfied with the explanations I found. Everyone talks about the most secure way to transfer the JWT token using HTTP headers instead of ...

Mismatch between ng-if and $index causing inconsistency

Is there a way to display a schedule with breaks after every group of matches within a week? For example, is it possible to have an <hr> tag appear after the first five matches in week 1 and then again after five matches in week 2? Currently, my code ...

Using jQuery to change date format from mm/dd/yy to yyyy-dd-mm

I need to transform a date in mm/dd/yy format from an ajax response into yyyy-mm-dd format using jquery. Is there a built-in function in jquery that can handle this conversion for me? ...

Passing events between sibling components in Angular 2Incorporating event emission in

Having some trouble emitting an event from one component to another sibling component. I've attempted using @Output, but it seems to only emit the event to the parent component. Any suggestions? ...

Is there a way to execute numerous queries upon the loading of a functional component with UseEffect, and then display the results within the render method

I've created a functional component that loops through an array on load to run async queries and populate a new array for display in the render method. import React, { useEffect, useState, useContext } from 'react'; import { AccountContext ...

Retrieve an XML file using JavaScript and store it within a variable

I am currently developing a PhoneGap Application utilizing jQuery Mobile. One of the requirements is to access an xml file stored on a remote server (accessible through a web server like http://www.example.com/myXmlFile.xml). My goal is to extract the cont ...

"Changes made to the AngularJS $scope are not being reflected in the DOM

Here are the snippets of code I am working with: The state (abbreviated for simplicity) .state('foo', { url: '/foo', templateUrl: 'path/to/template.html', controller:'fooCtrl', }) The controller contr ...

express.js application keeps crashing unexpectedly after running for a while

This express app is designed to be simple yet powerful. However, after sitting idle for a while without any requests, an unexpected error may occur: Example app listening on port 80! events.js:160 throw er; // Unhandled 'error' event ...

Creating a unique diagonal background in a React Native / Expo app

I'm creating a calendar feature for our application that displays availability. For days that have both check-ins and check-outs, happening at 12:00PM, I want to represent the day as half green and half pink, like this: https://i.sstatic.net/s97x7.pn ...