santa
santa

Reputation: 12512

Remove table column via loop

I have a table with 5 columns. I only show one row here:

<table>
<tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
</TR>
</table>

I want to create 5 clone tables, but in each clone I only need to keep one column of the original table.

<table>
<tr>
    <td>1</td>
</TR>
</table>

<table>
<tr>
    <td>2</td>
</TR>
</table>

<table>
<tr>
    <td>3</td>
</TR>
</table>

etc...

Here's what I've got so far:

for ( var i = 0; i < 5- 1; i++ ) {
    $('table:first').clone().insertAfter('table');
    $('table:last tr td:not(:nth-child(i))').remove();
}

The problem I have is in this line:

$('table:last tr td:not(:nth-child(i))').remove();

How do I delete all but this columns?

Upvotes: 2

Views: 369

Answers (3)

Chase
Chase

Reputation: 9362

Changing up your html and javascript a little bit to use id's to make selecting easier:

HTML:

   <div id="wrapper">
    <table id="my-table">
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
            <td>5</td>
        </tr>
    </table>
</div>

JAVASCRIPT:

$(function(){
    $.each($('#my-table td'),function(index,ele){
        $('#wrapper').append('<table><tr><td>'+$(ele).html()+'</td></tr></table>');
    });
    $('#my-table').remove();
});

Working example: http://jsfiddle.net/5TT5E/2/

Upvotes: 1

Ram
Ram

Reputation: 144689

You should concatenate the strings, i in your code is a character of a string, it doesn't refer to any variable, it should be:

$('table:last tr td:not(:nth-child('+i+'))');

Try this:

var $tbl = $('table:first');

for ( var i = 0; i < $tbl.find('td').length; i++ ) {
    $tbl.clone()
        .find('td')
        .not(':eq('+i+')')
        .remove()
        .end()
        .end()
        .insertAfter('table:last');
}

http://jsfiddle.net/v47GY/

Upvotes: 1

PSL
PSL

Reputation: 123739

Like this?

$('table').after($('table').find('tr:first td').map(function (i) {
     return $(this).closest('table').clone().find('td').not(':nth-child(' + (i+1) + ')').remove().end().end();
}).get());

Demo

if you have multiple table this would suit the best:

$('table').after(function () {
    return $(this).find('tr:first td').map(function (i) { //iterate through td of first tr
        return $(this)
               .closest('table').clone() //get the parent table and clone it
               .find('td').not(':nth-child(' + (i + 1) + ')') //select all td that are not in this index
               .remove() //remove all the previously selected tds from cloned table
               .end().end(); //back to the table
    }).get(); 
});

Demo

Upvotes: 1

Related Questions