Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

288
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda