Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery "select all except"

I am trying to select the first row of a table. Note: the first row is wrapped in a thead tag, so:

<table>
  <thead>
    <tr>  <!-- first row --> </tr>
  </thead>
  <tbody>
    <tr>  <!-- body --> </tr>
  </tbody>
  <tfoot>
    <tr>  <!-- body --> </tr>
  </tfoot>
</table> 

The 'select first row' tip could work if it wasn't for the wrapper tags. This is what I have tried but doesn't work:

 $("*:not(thead)", tableSelector).remove();

I.e., I would like to get rid off both tbody and tfoot selectors using a "not tfoot" selector. Because I want to remove everything else from the table except the <thead> and everything-inside-thead. So basically what I am trying to do is to select everything except thead and what's inside it; intutuively something like :not(thead *) could work, but doesn't.

My workaround is $("tbody, tfoot", tableSelector).remove(); but I would like to learn and understand how to use the opposite (not-selector).

like image 583
Martin Avatar asked Dec 13 '09 13:12

Martin


2 Answers

Using children() on the table selector will select only the direct children. You can filter this using your not selector.

$(tableSelector).children(':not(thead)').remove();
like image 21
tvanfosson Avatar answered Sep 19 '22 12:09

tvanfosson


Your question isn't exactly clear. To select the first row in a single table:

$("table tr:first")...

or the reverse:

$("table tr:not(:first)")...

will do it but that will break if there's more than one table (it will only select one row even if there are three tables). You can work around that with:

$("table").each(function() {
  $(this).find("tr:first")...
});

You can get all rows not in THEAD with:

$("table > :not(thead) > tr")...

Edit: I think you're over-complicating this. If you want to remove everything except THEAD and its contents, that's relatively simple:

$("table > :not(thead)").remove();

If you want to leave the TBODY and TFOOT elements in place change it to:

$("table > :not(thead) > tr").remove();
like image 138
cletus Avatar answered Sep 22 '22 12:09

cletus