Reputation: 782
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
Upvotes: 4
Views: 29227
Reputation: 144669
ID attributes must be unique, id
selector as it should, only returns the first matched element:
$(document).ready(function() {
$("div[id^='slid']").attr('id', function(i) {
return "slide" + ++i;
});
});
Upvotes: 13
Reputation: 23545
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/
Upvotes: 17
Reputation: 31131
Elements must have a unique ID. the each
function isn't iterating over the other divs. So find a way to select them all without violating that rule. The following works:
$("div").each(function(i)
Upvotes: 4