Emre
Emre

Reputation: 33

Changing list of items attributes with loop

I have a list of items.

<img id="item0" src="">
<img id="item1" src="">
.
.
.

When someone clicks a button, I need change the srcs based on id.(every src with different link)

I want to use something like at the below.

for (var i = 0; i < 10; i++) {
    $('#item' + i).attr('src', 'link')
} 

Is something like this possible? Actual code is this;

            for(var i=0;i<10;i++){

            var freeChampId=[];
            freeChampId.push(json['champions'][i].id);
            $.ajax({
                url:'https://global.api.pvp.net/api/lol/static-data/tr/v1.2/champion/'+json['champions'][i].id+'?&api_key='+key,
                type:'GET',
                datatype:'json',
                data:{},
                success:function(json){

                    $("img[id^=freeChamp_Out]").each(function(){

                        $(this).attr('src','http://ddragon.leagueoflegends.com/cdn/5.2.1/img/champion/'+json['key']+'.png')

                    });
                }
            })


        }

Every loop turn the key and the link changes.

Upvotes: 2

Views: 50

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82231

You don't need to iterate over elements if you are setting same src to all of them. For this you can use attribute starts with selector to target all the images along with attr to set the required attribute :

$("img[id^=item]").attr('src','link');

If the srcs are different:

$("img[id^=item]").each(function(){
  $(this).attr('src','link')
});

Upvotes: 3

Related Questions