kazinix
kazinix

Reputation: 30093

Copy elements and parents in jQuery?

I have a table:

<table>
    <thead>
        <th></th>
        <th>Col 1</th>
        <th>Col 2</th>
    </thead>

    <tbody>
        <tr>
            <th>R1</th>
            <td>Data</td>
            <td>Data</td>
        </tr>
        <tr>
            <th>R2</th>
            <td>Data</td>
            <td>Data</td>
        </tr>
        <tr>
            <th>R3</th>
            <td>Data</td>
            <td>Data</td>
        </tr>
    </tbody>
</table>

I want to copy all th and their parents (from tr up to table). The expected output should be:

<table>
    <thead>
        <th></th>
        <th>Col 1</th>
        <th>Col 2</th>
    </thead>

    <tbody>
        <tr>
            <th>R1</th>
        </tr>
        <tr>
            <th>R2</th>
        </tr>
        <tr>
            <th>R3</th>
        </tr>
    </tbody>
</table>

As you can see, I'm copying everything except td's.

I can do this in a step by step way (table first, then thead, so on and so forth). Is there a selector in jQuery that can do what I want in one line?

Upvotes: 1

Views: 52

Answers (1)

Praveen
Praveen

Reputation: 56501

I would clone the entire table, then remove all the tds and append back it to body.

var tab = $('table').clone();
tab.find('td').remove();
tab.appendTo('body');

Check this fiddle

Upvotes: 1

Related Questions