Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading