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

Working demo

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 

}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!