0

I have four images in a div like and adding the src to each image dynamically with jQuery in a loop as follows:

      jQuery("<img>",{src: BASE_URL+image_url)

do the image tag will like this:

    <img src="site_url/media/catalog/size_images/1.png"/>
    <img src="site_url/media/catalog/size_images/2.png"/>
    <img src="site_url/media/catalog/size_images/3.png"/>
    <img src="site_url/media/catalog/size_images/4.png"/>

now i want to add a different id to each image dynamically so the tag will be as follows:

    <img id="1" src="site_url/media/catalog/size_images/1.png"/>
    <img id="2" src="site_url/media/catalog/size_images/1.png"/>
    <img id="3" src="site_url/media/catalog/size_images/1.png"/>
    <img id="4" src="site_url/media/catalog/size_images/1.png"/>




       
Xabby
  • 435
  • 6
  • 26

3 Answers3

0

Try like this,

$("<img>",{src: BASE_URL+image_url, id: $('img').length});

However, you will need to append this image to document body, so that you get new id next time you call this code.

It can be,

$("<img>",{src: BASE_URL+image_url, id: $('img').length}).appendTo('#target');

Hope this help.

Vikas Nokhwal
  • 113
  • 10
0

for (x=0;x<$(target_div).children('img').length;x++){ var thisImg = $(target_div).children('img')[x]; thisImg.id = x; thisImg.src = BASE_URL+image_url; thisImg.alt = ''; }

Where 'target_div' is the div containing the img tags. Be sure to include the 'alt' attribute for valid html.

jarebones
  • 71
  • 5
0

you can add each image src and unique id dynamically with jQuery using for a loop like this:

   for (var i = 0; i < 4; i++) {
       $('div').append($('<img>',{id: "id" + i, src: BASE_URL+image_url}));
   }
shweta ramani
  • 382
  • 4
  • 6