brooks.johnson
brooks.johnson

Reputation: 55

How can I dynamically assign IDs to elements of a particular class using Jquery?

I've looked at other questions, but none of them have really helped me. I want to give IDs to a number of elements belonging to the same class without manually doing it. Here is my code that isn't working:

$curelem = $(".item:first");

for (var $i=0; i < $(".item").length; ++$i){
    $curelem.attr("id", "item" + $i);
    $curelem = $curelem.next('a');
}

Is it some small syntax error, or am I going about it entirely wrong?

Upvotes: 0

Views: 95

Answers (4)

michal
michal

Reputation: 1

$('.item').each(function(i) {
    this.setAttribute('id', "item" + i);
});

Upvotes: 0

Paul R
Paul R

Reputation: 2797

Use http://api.jquery.com/jquery.each/ to loop through elements:

$(".item").each(function( index, value ) {
  $(this).attr("id", "item"+index);
});

Upvotes: -1

Pat
Pat

Reputation: 66

$('.item').each(function (i, el) {
    el.id = "item" + i;
});

Upvotes: 1

jd182
jd182

Reputation: 3260

If you're using jQuery you can use jQuery's each() function:

var i = 0;

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

Upvotes: 1

Related Questions