Reputation: 55
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
Reputation: 1
$('.item').each(function(i) {
this.setAttribute('id', "item" + i);
});
Upvotes: 0
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