0
    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>..

5
  • 3
    the html is just a string,you know...$(...).append('<div>' + i + '</div>'); Commented Jan 22, 2016 at 14:04
  • @MarcB Guess my heads been in my code too long lol. Now you point it out it's obvious, sorry for wasting your time. Thanks for the help! Commented Jan 22, 2016 at 14:07
  • why do you want to enumerate classes? I'm pretty confident, that you try to solve a different problem with this aproach. Commented Jan 22, 2016 at 14:08
  • @Thomas i'm making a slideshow based off an array. I never know what the array length is. So I create all the divs onto the page, then adding the classes based on the array. Below i'll do some logic to then add an image based on the the incremented class names Commented Jan 22, 2016 at 14:14
  • so you use this enumerated class as some kind of index/id to fetch the nth item with your js-code? well, this is bad ... practice. you always know how many images you have added yet. you can always fetch the added nodes and select the nth item of that list. way better than messing around with css-classes Commented Jan 22, 2016 at 14:38

2 Answers 2

3
for (i = 0; i < arrayData.length; i++) {
  $(".swipe-wrap").append("<div class=\"final_"+i+"\">Hello!</div>");
  console.log('hello');
}
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

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.