views:

115

answers:

3

I have a code that looks like this:

<div id="wrapper">
     <img id="first"  class="images" src="img/nike.jpg" />
     <img  id ="second" class = "images" src="img/golden.jpg" />
     <img id = "third" class ="images" src ="img/a.jpg" />
     <img id = "fourth" class="images" src="img/God__s_Canvas_by_Delacorr.jpg" />
    </div>

I want to wrap each img with <a name = n> dynamically. So my solution was to do this:

$(".images").wrap('<a></a>')
$("#wrapper a").each(function(n) {
      $(this).attr('name', n);
     })

Is it possible to chain the 2 statements into 1 statement? I know that jQuery is particularly do elegant chaining so I think it's definitely possible. I just don't know how to yet.

+3  A: 

This isn't exactly the same because it doesn't wrap .images outside of #wrapper, but it's close. It creates the in the loop and immediately applies the attribute.

$('#wrapper img').each(function(n) { 
    $(this).wrap($('<a></a>').attr('name', n));
}
Dan Goldstein
Thanks!! Your solution works great.!
Keira Nighly
I didn't know that was possible. jQuery rocks! +1
Jose Basilio
+3  A: 

this might work...

$(".images").wrap('<a></a>').parent().each(function(n) {$(this).attr('name', n);});
Chris Brandsma
Thanks!! I never thought of parent(). I never thought it was just this simple.
Keira Nighly
Great answer. +1
Jose Basilio
A: 

I don't think you could, because you are referencing two separate collections of objects. The $() will return an array of matched items. In the case of your first implementation, you're pulling each image with a class of 'image' and wrapping them with the anchor tags. With your second implementation you're pulling all of the anchor tag elements within your 'wrapper' div, and applying the name attribute. These are two distinctly different collections, with the second one not even being available until after you've completed the first statement.

Now, Dan's implementation above might do the trick. Not the chaining you were looking for, but seems on the money.

Steve -Cutter- Blades