jquery how do you remove an element from a location a place in another and repeat x times – Education Career Blog

I’m trying to remove the first link-image below the h4 and prepend it to div.image-thumb. The code i use work’s fine if it’s just one table row “.tr-class” .

But when I have multiple rows, it copies all the link-image into .image-thumb. So if I have 10 rows, then each row will have 10 link-image each. How can I can get just the right link-image in the right spot The HTML and JS are below:

Thanks

<table>
<tr class="tr-class">
<td class="left-td">
    <div class="image-thumb">
    </div>
</td>
<td class="right-td">
    <h4>Header</h4>
    <a href="http://www.google.com"><img src="image.png" /></a>
    <p>this is my content</p>
    <a href="http://www.google.com">Read more</a>                
</td>       
</tr>

for(i = 0; i < 10; i++){
    $(".tr-class").eq(i).each(function(){
        var getImage = $(".tr-class .right-td h4").next().eq(i);
        $(getImage).prependTo(".tr-class .image-thumb");
    });
}

,

Try this:

$('.tr-class')
  .each(
    function()
    {
      $('.right-td h4 + a', this).appendTo($('.image-thumb', this));
    }
  );

,

I’m not sure how efficient it is, but this seems to work:

$(document).ready(
    function(){
        $('img').each(
            function(i){
                $(this).prependTo($('.image-thumb').eq(i));
            }
        );
    }
);

Demo at JS Bin

Assumptions made:

  1. That there will only be one image per .tr-class, it would probably be more reliable if you assigned a class to the images.

Leave a Comment