Bruno
Bruno

Reputation: 9027

Create variables dynamically with a For Loop Javascript

The title plus the following example are self-explanatory of what I don't achieve :-) The idea is to replace something + counter in order to make it work.

      for (var counter = 1; counter <= 6; counter++) {
        var something + counter = $('element' + counter);
        (something + counter).removeAttribute('class');
      }     

Upvotes: 2

Views: 2238

Answers (5)

Michael Sagalovich
Michael Sagalovich

Reputation: 2549

  for (var counter = 1; counter <= 6; counter++) {
    window[something + counter] = $('element' + counter);
    window[something + counter].removeAttribute('class');
  } 

after that there will be a set of fields in window object, named something1, something2 etc (if something == "something", of course)

Upvotes: 0

jli
jli

Reputation: 6623

Just do:

for (var counter = 1; counter <= 6; counter++) {
    $('element' + counter).removeAttribute('class');
}

Unless you wanted to store it outside of the loop, in which case use an array.

Upvotes: 3

JConstantine
JConstantine

Reputation: 3931

Why can't you just get rid of the var altogether??

for (var counter = 1; counter <= 6; counter++) {
    $('element' + counter).removeAttribute('class');
}

Upvotes: 2

Alex Turpin
Alex Turpin

Reputation: 47776

Use an array.

var something = [];
for (var counter = 1; counter <= 6; counter++) {
    something[counter] = $('element' + counter);
    something[counter].removeAttribute('class');
}

Upvotes: 2

Eran Zimmerman Gonen
Eran Zimmerman Gonen

Reputation: 4507

You could create an array, but much more simply:

  for (var counter = 1; counter <= 6; counter++) {
    $('element' + counter).removeAttribute('class');
  } 

Upvotes: 3

Related Questions