Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery attr add id to existing element

Tags:

jquery

attr

I have a bunch of imgs inside a div with a class on them, in my JS I have a for loop that re-sizes the images to fir inside a box without stretching

$('.gallery img')[i].attr('id', 'img' + i);

This is what I tried to get each img to have its own id like 'img1' 'img2' 'img3' etc

but it seems to not work

like image 500
Drew Avatar asked Jan 23 '26 02:01

Drew


1 Answers

Replace your for loop with:

$('.gallery img').each(function(i) {
    $(this).attr('id', 'img' + i);
    // You can also add more code here if you wish to manipulate each IMG element further
});

This block of code loops through each IMG element with a counter i incrementing after every instance, and this counter is suffixed to the id string.

like image 129
shrmn Avatar answered Jan 26 '26 23:01

shrmn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!