Search code examples
jqueryjquery-selectorsappendto

How to select multiple child elements with jQuery?


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!


Solution

  • 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.