user2108245
user2108245

Reputation: 15

loop the .append() with selector as variable

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

Upvotes: 0

Views: 139

Answers (3)

David Hellsing
David Hellsing

Reputation: 108480

You can also use a function as argument to append, might be cleaner and possibly faster in your case:

$('div').append(function() {
    return this.className;
});

http://jsfiddle.net/sSVL8/

Upvotes: 3

Starx
Starx

Reputation: 78971

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
}

Upvotes: 1

dlock
dlock

Reputation: 9577

<script type="text/javascript">
var a=3;
for (var i=0;i<a;i++)                       {                           
$("."+i).append(i); //this is what you need
}
</script>

<div class="0"></div> // expected: display 0
<div class="1"></div> // expected: display 1
<div class="2"></div> // expected: display 2

Upvotes: 2

Related Questions