pourmesomecode
pourmesomecode

Reputation: 4318

Javascript increment up within a loop

    for (i = 0; i < arrayData.length; i++) {
      $(".swipe-wrap").append("<div class=\"final\">Hello!</div>");
      console.log('hello');
    }

This is what I currently have. My arrayData is an array that changes each load.

How can I get it so my class final each for loop will have an counter like such : <div class="final_1">Hello!</div> , <div class="final_2">Hello!</div>..

Upvotes: 0

Views: 496

Answers (2)

Rajesh
Rajesh

Reputation: 24915

You should not perform DOM manipulation inside loops. Always perform bulk operation.

Try this:

var html = ""
for (i = 0; i < arrayData.length; i++) {
  html += '<div class="final_'+i+'">Hello!</div>';
  console.log('hello');
}
$(".swipe-wrap").append(html);

You can also use Array.forEach.

var html = ""
var arrayData = ["test1", "test2", "test3", "test4", "test5"];
console.log(arrayData);
arrayData.forEach(function(item, index) {
  html += '<div class="tile final_' + index + '">Hello ' +item+ '!</div>';
  console.log('hello');
});
$(".swipe-wrap").append(html);
.swipe-wrap {
  background: #eee;
  padding: 10px;
  border: 1px solid gray;
}
.tile {
  width: auto;
  padding: 10px;
  margin: 10px;
  background: #fff;
  border: 1px solid #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="swipe-wrap"></div>

Upvotes: 0

Darth
Darth

Reputation: 1651

for (i = 0; i < arrayData.length; i++) {
  $(".swipe-wrap").append("<div class=\"final_"+i+"\">Hello!</div>");
  console.log('hello');
}

Upvotes: 3

Related Questions