It would be easier if the table were put in sections correctly in the first place, using thead
and tbody
:
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>something</td>
</tr>
<tr>
<td>2</td>
<td>something else</td>
</tr>
</tbody>
</table>
Then it would be:
$("table.table > tbody > tr").remove();
Or if you need to keep a data row that’s identified by the text in the first column:
$("table.table > tbody > tr").filter(function() {
return $(this.firstElementChild).text().trim() != idToKeep;
}).remove();
Live Example:
setTimeout(function() {
var idToKeep = 2;
$("table.table > tbody > tr").filter(function() {
return $(this.firstElementChild).text().trim() != idToKeep;
}).remove();
}, 800);
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>something</td>
</tr>
<tr>
<td>2</td>
<td>something else</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
As it is, though, you’ll have to exempt the first row:
$("table.table tr:not(:first-child)").remove();
Or if you need to keep a data row that’s identified by the text in the first column and exempt the first row:
$("table.table tr").filter(function(index) {
return index !== 0 && $(this.firstElementChild).text().trim() != idToKeep;
}).remove();
setTimeout(function() {
var idToKeep = 2;
$("table.table tr").filter(function(index) {
return index !== 0 && $(this.firstElementChild).text().trim() != idToKeep;
}).remove();
}, 800);
<table class="table">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>something</td>
</tr>
<tr>
<td>2</td>
<td>something else</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You may be wondering why I used a descendant combinator (a space) rather than a child combinator (>
) in that one, when I used a child combinator in the previous one. The reason is that the browser will automatically wrap your rows in a tbody
element. So this would work as well:
$("table.table > tbody > tr:not(:first-child)").remove();
Or if you need to keep a data row that’s identified by the text in the first column and exempt the first row:
$("table.table > tbody > tr").filter(function(index) {
return index !== 0 && $(this.firstElementChild).text().trim() != idToKeep;
}).remove();
setTimeout(function() {
var idToKeep = 2;
$("table.table > tbody > tr").filter(function(index) {
return index !== 0 && $(this.firstElementChild).text().trim() != idToKeep;
}).remove();
}, 800);
<table class="table">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>something</td>
</tr>
<tr>
<td>2</td>
<td>something else</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>