views:

26

answers:

2

Hi,

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"&gt;&lt;img src="image.png" /></a>
    <p>this is my content</p>
    <a href="http://www.google.com"&gt;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");
    });
}
A: 

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.
David Thomas
Thanks! this works but only takes the image not both the image and link. The code provided by Thomas works as I need it to. But i'll still save this piece of code. it may be useful someday.
Tadtoad
A: 

Try this:

$('.tr-class')
  .each(
    function()
    {
      $('.right-td h4 + a', this).appendTo($('.image-thumb', this));
    }
  );
Thomas
Hey thanks! this one works perfectly! But can you explain what the "$('.right-td h4 + a', this)" does? i mean from the comma and "this".
Tadtoad
`this` in that case works as a context for the selector. You can use a jQuery object, a DOM Object, or another selector as a context. So it allows you to constrain your selectors to subsets of the DOM tree. `this` specifically refers to the current element in the `each()` loop, so `$('.right-td h4 + a', this)` returns all a-elements that are immediately adjacent siblings to h4-elements, that are offsprings of elements with the class right-td, but only inside the current `.tr-class`.
Thomas