vector
vector

Reputation: 7576

Looping over table rows and moving contents from one cell to another with jQuery

I'm trying to loop over TRs and take contents from one cell and append them to another.

$('.tableRow').each( function(){
    $( '.cell2', this).wrapInner("<div class='tempDiv'></div>");
    $('.tempDiv', this ).appendTo( ".cell1", this );
});

... but what I'm getting is for example, if a table has 4 rows, cell1 will get tempDiv appended at least 8 times.

fiddle: http://jsfiddle.net/HenriPablo/TFgN3/1/

Upvotes: 2

Views: 289

Answers (3)

Niffler
Niffler

Reputation: 1710

Is this the result you were looking for?

$('.tableRow').each( function(){
    $(this).find('.cell2').wrapInner("<div class='tempDiv'></div>");
    $(this).find('.tempDiv').appendTo( $(this).find('.cell1') );
});

Here's a fiddle: http://jsfiddle.net/Niffler/kLyHy/

The way it was written, the data from each cell was appended to each instance of the class "cell1"...

Upvotes: 2

amit_g
amit_g

Reputation: 31250

Are you looking for this?

$('.tableRow').each( function(){
    $(".cell1", this)
        .append($("<div class='tempDiv'></div>")
                    .append($( '.cell2', this).html())
               );
});

Upvotes: 1

random_user_name
random_user_name

Reputation: 26160

I'm sure there is a cleaner way to do this, but the quickest way to get your code to work is to make some changes to the jQuery:

$('.tableRow').each( function(){
    $(this).find('.cell2').wrapInner("<div class='tempDiv'></div>");
    $(this).find('.cell1').append($(this).find(".tempDiv"));
});

Here's a Fiddle

Upvotes: 3

Related Questions