how to remove all elements from a table row except first th

I have a table row like this

This row is generated using a for loop in jquery ,there can be more than 1 row .I want to remove all elements except first of each row ,I have tried like this

for (var i = 0; i < o.result[0].length; i++) {
  //$("#fullSelection"+i).empty(); //its working
  //$("#fullSelection"+i).not(':first').remove();//not working
  $("#fullSelection" + i).slice(1).remove(); //not working
}
<tr id='fullSelection0' style='display: table-row;'>
  <th class='predict'>

  </th>
  <td>
  </td>
  <td>
  </td>
  <td>
  </td>
</tr>

Any idea how to achieve it??

3 answers

  • answered 2018-11-08 06:28 Mamun

    An HTML table has two kinds of cells:

    Header cells - contains header information (created with the <th> element)

    Standard cells - contains data (created with the <td> element)

    In HTML table design, you should not combine both th and td inside the same tr.

    I think you do not need the looping for that. You can simply target and remove all the children except the first in each tr with jQuery selector like:

    $('tr td,th').not(':first-child').remove();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
      <tr id='fullSelection0' style='display: table-row;'>
        <th class='predict'>Col-Test</th>
        <td>1</td>
        <td>2</td>
        <td>3</td>
      </tr>
      
      <tr id='fullSelection1' style='display: table-row;'>
        <th class='predict'>Col-Test2</th>
        <td>11</td>
        <td>22</td>
        <td>33</td>
      </tr>
    </table>

  • answered 2018-11-08 06:55 brk

    You can do it pure css using not & :first--child

    tr>td:not(:first-child) {
      display: none;
    }
    <table>
      <tr id='fullSelection0' style='display: table-row;'>
        <th class='predict'>Col-Test</th>
        <td>1</td>
        <td>2</td>
        <td>3</td>
      </tr>
    
      <tr id='fullSelection1' style='display: table-row;'>
        <th class='predict'>Col-Test2</th>
        <td>11</td>
        <td>22</td>
        <td>33</td>
      </tr>
    </table>

  • answered 2018-11-08 07:11 Hamza Haider

    You can do it by the following way.

    $("tr > td:not(:first-child)").remove();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
      <tr id='fullSelection0' style='display: table-row;'>
        <th class='predict'>Col-Test</th>
        <td>1</td>
        <td>2</td>
        <td>3</td>
      </tr>
      
      <tr id='fullSelection1' style='display: table-row;'>
        <th class='predict'>Col-Test2</th>
        <td>11</td>
        <td>22</td>
        <td>33</td>
      </tr>
    </table>