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>..
asked Jan 22, 2016 at 14:02
pourmesomecode
4,38812 gold badges55 silver badges91 bronze badges
2 Answers 2
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
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>
answered Jan 22, 2016 at 14:42
Rajesh Dixit
25.1k5 gold badges52 silver badges86 bronze badges
Comments
default
$(...).append('<div>' + i + '</div>');