user3571265
user3571265

Reputation: 3

Append an element to a different element with the corresopnding index using jQuery

I have some images and their descriptions, currently loading in separate divs:

<div id="slideshow">

<div class="slide">IMAGE 1</div>

<div class="slide">IMAGE 2</div>

<div class="slide">IMAGE 3</div>

</div><!--end slideshow-->

<div id="captions">

<div class="slide"><div>CAPTION 1</div></div>

<div class="slide"><div>CAPTION 2</div></div>

<div class="slide"><div>CAPTION 3</div></div>

</div><!--end captions-->

I would like to move each caption to its corresponding image. It can be appended to either the image tag or its parent div. Hoping for this:

<div id="slideshow">

<div class="slide">IMAGE 1</div>

<div>CAPTION 1<div>

<div class="slide">IMAGE 2</div>

<div>CAPTION 2<div>

<div class="slide">IMAGE 3</div>

<div>CAPTION 3<div>

</div><!--end slideshow-->

I tried something here, but it attached every caption to each image.

<script>
$('#captions .slide').each(function(){
        if ($(this).index().valueOf() == $('#slideshow .slide').index().valueOf()){
            $(this).detach().appendTo('#slideshow .slide');
            } else {
            $(this).hide();
            }

        });
</script>

I know this code is probably headed in the wrong direction. I'm happy to scrap it and start over.

Upvotes: 0

Views: 49

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156624

I think this is roughly what you're going for:

$('#captions .slide').each(function(i, v) {
    $('div', v).appendTo($('#slideshow .slide')[i]);
});
$('#captions').remove();

Upvotes: 2

Related Questions