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
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!