February 27, 2013
loop the .append() with selector as variable
Question by user2108245
I am trying to loop the .append() function in order to change the selector each time with different value. But, I don’t know the syntax for the selector in order to meet my target. So, how to change it? Thanks so much!
Ka Ho
<script type="text/javascript">
var a=3;
for (var i=0;i<a;i++) {
$i.append(i);
}
</script>
<div class="0"></div> // expected: display 0
<div class="1"></div> // expected: display 1
<div class="2"></div> // expected: display 2
Answer by Starx
First of all numeric class and ids are not supported that much as you think it is.
Update your HTML to something like this
<div class="box-0"></div>
<div class="box-1"></div>
<div class="box-2"></div>
Then you can use the script provided by deadlock in his answer.
var a=3;
for (var i=0;i<a;i++) {
$(".box-"+i).append(i); //this is what you need
}