Reputation: 765
Okay I dont think anyone has covered this yet.
I have a div with x amount of images inside it. I need to add the class 00x to each image where the x starts at 1 and goes up everytime for each image. I have tried doing this with a for in statement however cant seem to make it work. I am using the jquery library so feel free to suggest jQuery related fixs. Here is my html:
<div id="fixed">
<img src="/prodimages/Ad060-2.jpg" />
<img src="/prodimages/Ad060-2.jpg" />
<img src="/prodimages/Ad060-2.jpg" />
</div>
so I need it to select all images inside #fixed and then add the class 00 + i where i++ for each image. I need something like a php foreach. I dont really understand how for in works.
Please advise. :)
Upvotes: 1
Views: 867
Reputation: 4368
In case the number of images should exceed 10, use something like:
function pad_number(num) {
if(num < 10) return '00' + num;
else if (num < 100) return '0' + num;
return num;
}
jQuery('#fixed img').each(function(index, el) {
jQuery(el).addClass(pad_number(index));
});
Upvotes: 5
Reputation: 33865
Something like this should do it:
$("#fixed img").each(function(i) {
$(this).addClass("00" + i);
};
Upvotes: 1
Reputation: 10556
$("#fixed img").each(function(i){
this.addClass($.strPad(i,3));
});
$.strPad = function(i,l,s) {
var o = i.toString();
if (!s) { s = '0'; }
while (o.length < l) {
o = s + o;
}
return o;
};
source padding function: http://stv.whtly.com/2009/02/27/simple-jquery-string-padding-function/
I hope this helps :)
Upvotes: 0