captainduh captainduh - 1 month ago 16
Javascript Question

jQuery Selectors Removing table rows that meet two conditions

I'm trying to understand what techniques are employed when you have an operation that only runs when multiple conditions are met in jQuery. I don't know if a filter is the answer or not.

In my example, I have multiple tables on a page. I want to remove the rows of the table that meet two conditions. The first condition is that the row must not be the first row of the table (first child of the table element). The second condition is the row must not have any styling applied to it (no style element declared). I'm confused on the notation for a complex selector. I'm trying to go beyond the simple selectors now.

In my example, the table to use is labeled gvBigTable. I have the following:

$("#gvBigTable table tbody tr.not('style')").remove();
$("#gvBigTable table tbody tr.not(first-child)".remove();


I want to combine these conditions so that both must be met in order for the row to be removed. Any help is appreciated. Thanks.

Answer

You have not used :not() correctly. You can do it like following.

$("table tbody tr:not(':first-child'):not('[style]')").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <td>111</td>
        </tr>
        <tr>
            <td>222</td>
        </tr>
        <tr style="">
            <td>333</td>
        </tr>
        <tr>
            <td>444</td>
        </tr>
    </tbody>
</table>

UPDATE: according to the suggestion of David Thomas a pure CSS solution is like following.

table tbody tr:first-child ~ tr:not([style]) { 
    display: none; 
}

table tbody tr:first-child ~ tr:not([style]) {
  display: none;
}
<table>
  <tbody>
    <tr>
      <td>111</td>
    </tr>
    <tr>
      <td>222</td>
    </tr>
    <tr style="">
      <td>333</td>
    </tr>
    <tr>
      <td>444</td>
    </tr>
  </tbody>
</table>

If you don't want to use display: none then you can use the selector table tbody tr:first-child ~ tr:not([style]) with jQuery to remove the rows.

Comments