October 28, 2010
jQuery remove elements by condition
Question by plutov
I have some tr elements in table:
<table>
<tr id="tr_level_1">...</tr>
<tr id="tr_level_2">...</tr>
<tr id="tr_level_3">...</tr>
<tr id="tr_level_4">...</tr>
<tr id="tr_level_5">...</tr>
</table>
In Javascript I have the next variable:
var levels = 3;
I want to delete all tr’s where number in id is more than levels
. And if levels
is more than number of tr’s – adding tr’s after last.
Thanls a lot.
Answer by netadictos
Try this:
var levels = 3;
$("table tr:gt("+(levels-1)+")").remove();
I substract one because this expression (“gt”: greater than) is 0-based index.
For the second part of your question try this:
http://www.jsfiddle.net/dactivo/fADHL/
if($("table tr").length<levels){
//the code here for less than levels
}
else
{
$("table tr:gt("+(levels-1)+")").remove();
}
Answer by Starx
try this
var total = $("#table").find('tr').length;
var levels = 3;
if(levels<=total) {
for(levels=levels;levels<=total;levels++) {
$("#tr_level_"+levels).remove();
}
}
else {
$("#table").append("<tr id="tr_level_"+total+1+"">..</tr>");
// this will add the element with tr_level_6 at the end
}