views:

40

answers:

3

Hello. I have 10 or so images coming in from flickr. At the moment they just come in as images with no individual ID or Class names.

So I have:

<img src="images/01.jpg" width="300" height="273" />
<img src="images/01.jpg" width="300" height="273" />
<img src="images/01.jpg" width="300" height="273" />
<img src="images/01.jpg" width="300" height="273" />

...and so on. What I want to do is have:

<img id="image1" src="images/01.jpg" width="300" height="273" />
<img id="image2" src="images/01.jpg" width="300" height="273" />
<img id="image3" src="images/01.jpg" width="300" height="273" />
<img id="image4" src="images/01.jpg" width="300" height="273" />

But because they are being brought in via jQuery, and not manually, I'm unsure how to add these ID's, in order, to the images. Each needs to be styled differently.

Any ideas?

+2  A: 

You can use:

jqueryEl.attr("id", "someId");

or:

jqueryEl.addClass("newClass")

where jQueryEl is a wrapped element. Or, if you have a set of images, you might find attr's function option helpful:

jquerySet.attr("id", function(index)
                     {
                       return "image" + (index + 1);
                     });

This is actually similar to an example in the attr docs.

Matthew Flaschen
+1 nice use of `attr` with callback! Your parameter name is a little misleading since its the `index` not the `id`, but still, great answer!
Doug Neiner
@Doug, thanks, I've corrected it now.
Matthew Flaschen
+5  A: 

use the callback function of your ajax...

if you have something like this,

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&amp;tagmode=any&amp;format=json&amp;jsoncallback=?", function (data) {
    $.each(data.items, function (i, item) {
        $("<img/>").attr({"src":item.media.m, 'id': 'images' + i}).appendTo("#images");
    });
});
Reigel
A: 

If you want to post the code that fetches the images, it probably could be better integrated there. However, you could also just add this code after the images have been added. Lets pretend the images are added to a div with the id of flickr:

$("#flickr img").each(function (i, image){
  image.id = "image" + (i + 1);
});

Thats it! Now each image will have image1, image2, etc as the id, in order.

Doug Neiner