DoYouWantaWebsite
DoYouWantaWebsite

Reputation: 141

Jquery: Dynamic adding <id> depending on <div>

Let's dynamically add IDs on our DIV tag, depending on the number of DIVs

<div class="panel" id="">
  ...
  ...
</div>
<div class="panel" id="">
  ...
  ...
</div>
<div class="panel" id="">
  ...
  ...
</div>

the result that we would like to achieve is using jquery

<div class="panel" id="1">
  ...
  ...
</div>
<div class="panel" id="2">
  ...
  ...
</div>
<div class="panel" id="3">
  ...
  ...
</div>

i tried to do a code like this but it is not working

$panel.each(function(i) {
  $(this).attr('id', ($(i+1)));

Upvotes: 0

Views: 2932

Answers (4)

user745229
user745229

Reputation:

 $(document).ready(
        function () {
            var counter = 1;
            $(".panel").each(
                function () {
                    $(this).attr("id", counter);
                    counter++;
                }
            );
        }
);

Upvotes: 0

njbair
njbair

Reputation: 1982

i=0;
$('.panel').each(function() {
    i++;
    $(this).attr('id', i);
});

Upvotes: 0

Guy
Guy

Reputation: 13296

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

http://jsfiddle.net/rjptR/

Upvotes: 1

Andrey Fedoseev
Andrey Fedoseev

Reputation: 5382

The problem is with the last line:

  $(this).attr('id', ($(i+1)));

Why do you wrap i+1 with ($())?

It should be just

  $(this).attr('id', i+1); 

Upvotes: 0

Related Questions