1

I want to grab an HTML element using a variable which contains a string which is also the name of my HTML element. When calling the variable containing the string I don´t want to get the string itself but the ID of the HTML element which has the same name. How can I do that?

In particular, I want to do this:

I´ve got some objects:

<canvas width="250" height="250" id="output_1"></canvas>
<canvas width="250" height="250" id="output_2"></canvas>
<canvas width="250" height="250" id="output_3"></canvas>

In the script I make a string which equals the ID:

var aktuellerCanvas;
var count = -1;

Later, I want to grab the elements by ID, first "output_1", then "output_2" and so on.... I tried this, but I was not successful. I guess, I´m only calling the string in the variable aktuellerCanvas.

count++;
aktuellerCanvas = "output_" + (count % 3 ++);

aktuellerCanvas.putImageData(image, 0, 0, 0, 0, width, height);

Can you help me?

4
  • your aktuellerCanvas is just a string, not a html element Commented Jun 28, 2013 at 9:01
  • document.getElementById("output_" + (count % 3 ++))? Commented Jun 28, 2013 at 9:01
  • count % 3 ++ is not legal. You probably meant ++count % 3. Commented Jun 28, 2013 at 9:02
  • as count is incremented before I don't think it is required at all Commented Jun 28, 2013 at 9:03

4 Answers 4

1

You can use document.getElementById() here because, it you have the id of the element as the string

aktuellerCanvas = document.getElementById("output_" + (count % 3))
Sign up to request clarification or add additional context in comments.

Comments

1

aktuellerCanvas = document.getElementById("output_" + (count % 3 ++))

Also (count % 3 ++) is not valid

You may need (count++ % 3 ) or (++count % 3)

Comments

0

If the ids are in the range of [1, 3] the code to return the element identifier name should be this:

aktuellerCanvasId = "output_" + (++count % 3 + 1);

Assuming you start with count == -1, the above statement will return output_1 the first time you call it, output_2 for the second time and output_3 for the third; and then it repeats.

Afterwards you get the actual element using getElementById():

aktuellerCanvas = document.getElementById(aktuellerCanvasId);

Comments

0
aktuellerCanvas = document.getElementById("output_" + (count++ % 3));

will do the job !

But caution, you cannot apply "putImageData" directly on the HTML element, you have to apply it on its 2D context ! See the code below:

var ctx = aktuellerCanvas.getContext("2d");
ctx.putImageData(image, 0, 0, 0, 0, width, height);

1 Comment

The W3School doc about "PutImageData": w3schools.com/tags/canvas_putimagedata.asp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.