Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over divs with same ID and adding number

Tags:

jquery

loops

I am trying to iterate over every div with the the id 'slide' and add a number to the end (e.g slide1, slide2, etc)

I have been able to have a series of classes added to each div, but I can only get the same code to rename the first slide, not the rest of them.

$(document).ready(function() {
 $("#slide").each(function(i) {
    $(this).attr('id', "slide" + (i + 1));
 });
});​

and jsfiddle here http://jsfiddle.net/YsvCe/1/

Thanks in advance

like image 871
aroundtheworld Avatar asked Nov 28 '22 03:11

aroundtheworld


1 Answers

You should use classes rather than ids for multiple elements.

<div class="slide">hello</div>

...

$(document).ready(function() {
    $(".slide").each(function(i) {
        $(this).attr('id', "slide" + (i + 1));
    });
});​

Example: http://jsfiddle.net/QaB76/

like image 55
grc Avatar answered Dec 11 '22 03:12

grc