Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

285
Vistas
How can I assign value of get element by id into array in Javascript?

as you can see I have a lot of repetitive code below...

var c0 = document.getElementById('c0');
var c1 = document.getElementById('c1');
var c2 = document.getElementById('c2');
var c3 = document.getElementById('c3');

var c4 = document.getElementById('c4');
var c5 = document.getElementById('c5');
var c6 = document.getElementById('c6');
var c7 = document.getElementById('c7');

var c8 = document.getElementById('c8');
var c9 = document.getElementById('c9');
var c10 = document.getElementById('c10');
var c11 = document.getElementById('c11');

c0.addEventListener("click", function() {revealCard(0); });
c1.addEventListener("click", function() {revealCard(1); });
c2.addEventListener("click", function() {revealCard(2); });
c3.addEventListener("click", function() {revealCard(3); });

c4.addEventListener("click", function() {revealCard(4); });
c5.addEventListener("click", function() {revealCard(5); });
c6.addEventListener("click", function() {revealCard(6); });
c7.addEventListener("click", function() {revealCard(7); });

c8.addEventListener("click", function() {revealCard(8); });
c9.addEventListener("click", function() {revealCard(9); });
c10.addEventListener("click", function() {revealCard(10); });
c11.addEventListener("click", function() {revealCard(11); });

So I want to shorten this obviously by creating for loop. I did this in following way:

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

Unfortunately it didn't work.. I didn't find similar question so here I am. I do not have any errors in console so it's strange for me. Everything seems to be correct but still it does not work. I would be grateful if you helped me.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

A more preferable way would be to add a class to the joint parent of those elements, and use addEventListener on it. That way, with event bubbling, you can listen to a click event and act according to the specified element.

For example,

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/

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can modify the code and use it like this -

let obj = {};
for(let i=0; i<12; i++)
{
    obj[`c${i}`] = document.getElementById(`c${i}`);
    obj[`c${i}`].addEventListener("click", function() {revealCard(i); });
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You didn't declare your i variable which caused a bug, try 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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda