count classes and assign different id

I have three elements with the same class:

<div class="hotel_price">30.00</div>
<div class="hotel_price">35.00</div>
<div class="hotel_price">36.00</div>

my function:

<script>
  $(document).ready(function() {
    for(i=1;i<=3;i++){ $('.hotel_price').attr('id','hotel_'+i);}
  });
</script>

the result:

<div id="hotel_3" class="hotel_price">30.00</div>
<div id="hotel_3" class="hotel_price">35.00</div>
<div id="hotel_3" class="hotel_price">36.00</div>

and I need:

 <div id="hotel_1" class="hotel_price">30.00</div>
    <div id="hotel_2" class="hotel_price">35.00</div>
    <div id="hotel_3" class="hotel_price">36.00</div>

Upvotes: 2

Views: 148

Answers (5)

prograhammer
prograhammer

Reputation: 20590

Using jQuery's .eq()

$(document).ready(function() {
    for(i=1;i<=3;i++){ $('.hotel_price').eq(i-1).attr('id','hotel_'+i); }
});

Upvotes: -1

Achrome
Achrome

Reputation: 7821

You want to use the each() function to iterate over the elements.

$('.hotel_price').each(function(i) {
    $(this).attr('id', 'hotel_' + i);
});

Upvotes: 1

origin1tech
origin1tech

Reputation: 749

$(document).ready(function () {
    $('div.hotel_price').each(function (ctr) {
         $(this).attr('id', 'hotel_' + (ctr +1));
     });
});

Upvotes: 0

Paolo Bergantino
Paolo Bergantino

Reputation: 488384

You want:

$('.hotel_price').attr('id', function(i) { return 'hotel_' + i; });

The reason your code is not working is because you are setting the IDs of all 3 elements each time through the loop:

for(i=1;i<=3;i++) {
   // at this point, there is nothing specifying which .hotel_price to modify
   // so all 3 of them will be changed each time around
   // using .attr(name, fn) or .each(fn) is the jQuery way to do this.
   $('.hotel_price').attr('id','hotel_'+i);
}

Upvotes: 8

Barmar
Barmar

Reputation: 780843

When you write $('.hotel_price').attr(...) you're setting the attribute of all elements that match the selector. You need to iterate over the elements, operating on each of them in turn so you can assign different attributes to each. jQuery's each() method is used for this.

var i = 1;
$('.hotel_price').each(function() {
    $(this).attr('id','hotel_'+i);
    i++;
});

Upvotes: 0

Related Questions