Belindariot
Belindariot

Reputation: 35

Repeat a step in a for loop

I have a for loop.

for (var i = 0; i < 15; i++) {
            var gridResult = Math.floor(Math.random() * 77) + 1;
            $(['data-x='+gridResult+']').append('<div></div>');
        }

<html>
<div class="grid" data-x="0"></div>
...
<div class="grid" data-x="77"></div>

Now I want it to repeat the step, if it detects that there was allready an element assigned in one of the previous iterations, so there won't be 2 divs assigned to the same element.

I tried doing that by using:

if ($(this).children().length > 1) {
                    return;
                }

but that didn't work out since there were still elements with 2 divs attached.

Thanks in advance.

Upvotes: 1

Views: 710

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve your goal you can add the if condition within the loop. If a child element is found within the target you can decrement 1 from i to force the loop to repeat again. Try this:

for (var i = 0; i < 15; i++) {
  var gridResult = Math.floor(Math.random() * 77) + 1;
  let $target = $(['data-x=' + gridResult + ']');
    if ($target.children().length) {
      i--; // repeat the action
    } else {
      $target.append('<div></div>');
    }
  }
}

Upvotes: 2

Related Questions