johnny_dev johnny_dev - 5 months ago 14
jQuery Question

jQuery: Return multiple dynamic variables from a FOR LOOP

I want to count all elements with a class of

.step
then make a
for
loop and return variables that select each of the corresponding element. Here's my code:

var steps = $('.step').length;
var i = 0;

for (var i = 0; i < steps; i++) {
return var step + i = $('.step' + i);
}


EDIT: To make myself clear, instead of doing it like this:

var step1 = $('.step1.');
var step2 = $('.step2.');
// etc..


I want to use a
for
loop to get each element with a class of
.step
and return each one in a different variable, like so:
step1
,
step2
, etc. How can I do this?

Answer

If you want all the data in an array, you can try something like this:

var data = $(".step").map(function(s, index) {
  return $(".step" + (s + 1));
});
console.log(data)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="step step1">1</div>
<div class="step step2">2</div>
<div class="step step3">3</div>
<div class="step step4">4</div>
<div class="step step5">5</div>
<div class="step step6">6</div>

But I would rather suggest you to store data in an object. This would be easier to access.

var obj = {};
$(".step").each(function(i, el) {
  var _i = i + 1;
  obj["step" + _i] = $(".step" + _i);
});

console.log(obj)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="step step1">1</div>
<div class="step step2">2</div>
<div class="step step3">3</div>
<div class="step step4">4</div>
<div class="step step5">5</div>
<div class="step step6">6</div>