Use $(this)
instead of img
in each callback function
var img = $('img');
img.each(function(item){
$(this).attr('id', item);
});
Note: Index starts with 0
Question
I have 32 images, and I was hoping that the following snippet would assign to each img tag an id starting from 1 to 32, but it assigns 32 to all of the ids. Where am i doing wrong?
var img = $('img');
img.each(function(item){
img.attr('id', item);
});
Solution
Use $(this)
instead of img
in each callback function
var img = $('img');
img.each(function(item){
$(this).attr('id', item);
});
Note: Index starts with 0
OTHER TIPS
try:
var img = $('img');
img.each(function(ind,item){
$(item).attr('id', ind);
});