How to pass a variable as a parameter to "getElementById"

Asked

Viewed 196 times

0

I need to color several canvas, the code below colors one of them

var canvas1 = document.getElementById("a1");
var ctx1 = canvas1.getContext('2d');
ctx1.fillStyle = cor; //aqui vai a cor html
ctx1.fillRect(0, 0, 300, 300);

I can automate color through an array type arrcor = [#F95201,#AB31AA,#E70078...], something like:

ctx1.fillStyle = arrcor[i];

But I need each color of this to go to a different canvas according to the ID, something like id="a1", id="a2", id="A3"... So I need to automate this change, I tried to pass a variable in, like,:

rolln = "a" + i;
var canvas1 = document.getElementById(rolln);
var ctx1 = canvas1.getContext('2d');
ctx1.fillStyle = cor; //aqui vai a cor html
ctx1.fillRect(0, 0, 300, 300); 

ou

var canvas1 = document.getElementById("a" + i);
var ctx1 = canvas1.getContext('2d');
ctx1.fillStyle = cor; //aqui vai a cor html
ctx1.fillRect(0, 0, 300, 300); 

But it doesn’t work, as I do to change the id, according to i (counter) inside the loop since getElementById accepts only a string as parameter?

  • 1

    It should work. See the example in the OS in English https://stackoverflow.com/questions/22068387/can-i-use-a-string-variable-in-document-getelementbyid . Is your canvas in the DOM? This could be it...

  • 1

    dib, it should work since "a" + i here is as much a string as "a1". See if the console shows an error, if document.getElementById("a" + i) find nothing, will give an error on the line var ctx1 = canvas1.getContext('2d');.

  • Exactly, that same mistake.

1 answer

1

You can place the association within an array of objects, for example:

var arrayCores = [
     {"nome_elemento": "a1", "cor": "#FFFFFF"}, 
     {"nome_elemento": "a2", "cor": "#AB31AA"}
];

for (var i in arrayCores){
   var canvas1 = document.getElementById(arrayCores[i]["nome_elemento"]);
   var ctx1 = canvas1.getContext('2d');
   ctx1.fillStyle = arrayCores[i]["cor"];
   ctx1.fillRect(0, 0, 300, 300); 
}
  • Thanks for your reasoning, the point is that the id’s do not change, they will always be a1, a2, A3..., but the colors yes, they will be passed by a calculation.

  • Sorry for the delay, but in case it would be enough to have the Color arrayCores populated after knowing which color was for each element

Browser other questions tagged

You are not signed in. Login or sign up in order to post.