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);
});
Was it helpful?

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

DEMO

OTHER TIPS

try:

var img = $('img');

img.each(function(ind,item){
    $(item).attr('id', ind);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top