Home > Software engineering >  jquery remove all td's from a tr but not the first
jquery remove all td's from a tr but not the first

Time:04-08

i have a table with multiple rows and cols. I clone the table and like to remove all td's but not the first one

for example:

<table id="cloneto">
<tr><td>First</td><td>Second</td>....<tr>
<tr><td>First</td><td>Second</td>....<tr>
<tr><td>First</td><td>Second</td>....<tr>
</table>

container.append($("#cloneto").clone().remove(?????))

The result of the cloned table should look like:

<table id="cloneto">
<tr><td>First</td><tr>
<tr><td>First</td><tr>
<tr><td>First</td><tr>
</table>

CodePudding user response:

You can use an nth-child selector to pick all the <td> elements that are after the first in each row

const container = $("#container");

container.append(
  $("#cloneto")
    .clone()
    .find("tr td:nth-child(n 2)") // find the 2nd and onward cells
    .remove()                     // remove them
    .end()                        // return to the clone
);
table { table-layout: fixed; border-collapse: collapse; border: 1px solid; margin: 1rem; }
td { border: 1px solid; padding: .2rem; }
#container { background-color: #ccc; padding: .5rem 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<table id="cloneto">
<tr><td>First</td><td>Second</td><td>Third</td><tr>
<tr><td>First</td><td>Second</td><td>Third</td><tr>
<tr><td>First</td><td>Second</td><td>Third</td><tr>
</table>

<div id="container"></div>

  • Related