2

Total jQuery newbie here. Using this example HTML, I want to use jQuery to move every span.caption inside the preceding A tag.

Before:

 <ul class="gallery">
 <li><a href="http://mysite.com/mural.jpg"><img src="mural.jpg"/></a>     
 <span class="caption">Nice mural</span>
 </li>
 <li><a href="http://mysite.com/car.jpg"><img src="car.jpg"/></a>     
 <span class="caption">New car</span>
 </li>
</ul>

Desired result:

 <ul class="gallery">
 <li><a href="http://mysite.com/mural.jpg"><img src="mural.jpg"/>     
 <span class="caption">Nice mural</span></a>
 </li>
 <li><a href="http://mysite.com/car.jpg"><img src="car.jpg"/>     
 <span class="caption">New car</span></a>
 </li>
</ul>

I tried $('ul.gallery li span.caption').appendTo($('ul.gallery li a img')); but it selects every span.caption and positions them inside the first img tag.

I think I need to use a parent-child selector in some way, but confused about that.

Thanks!

Jason
  • 1,167
  • 1
  • 9
  • 10

3 Answers3

4

You can use the .each method to iterate over the matched set of .caption elements, and prev to access the immediately preceding element (the a in your case):

$(".caption").each(function() {
    var caption = $(this);
    caption.appendTo(caption.prev()); 
});

Here's a working example (inspect the source with Firebug to see the result)

James Allardice
  • 164,175
  • 21
  • 332
  • 312
3

You can flip your logic a bit and use append().

$('.gallery a').append(function() {
    return $(this).nextAll('.caption');
});

jsFiddle.

I find this easier to read myself, but YMMV.

alex
  • 479,566
  • 201
  • 878
  • 984
0
$('.caption').each(function(){$(this).prev().append($(this))});
Salt Hareket
  • 764
  • 7
  • 18
  • To make it a little less noisy when doing it on one line, you can omit constructing the jQuery object when passing `this` to `append()`. – alex Dec 21 '11 at 23:24