maaz
maaz

Reputation: 3664

Jquery-Delete all the row if first td of row does not have the id with given value

I have a table with many rows. from which i want to delete all the rows except the row, of which first td has a given id.

i am in half way

 <tr>
   <td id="1" class="td_link" onclick="viewPointDetails(1)">Barrackpur</td>
   <td class="td_link" id="11" class="edit_client" onclick="editPoint(1)">India</td>
 </tr>


 <tr>
   <td id="2" class="td_link" onclick="viewPointDetails(2)">Madiwala</td>
   <td class="td_link" id="11" class="edit_client" onclick="editPoint(1)">India</td>
 </tr>

and my jquery;

   $('tr').each(function () {   
       if first td does not have given  id say 1  then delete this row.
   });  

my First row is header. so i dont want this to be checked(do not want this row to be deleted).

Upvotes: 0

Views: 827

Answers (2)

Anil D
Anil D

Reputation: 2009

Try this

$(document).ready(function () {
     $('tr').each(function () {   
      if($(this).find("td:first").attr("id") == 2)
      {
        $(this).remove();
      }
  });
});

Upvotes: 0

James Allardice
James Allardice

Reputation: 166001

You should be able to achieve this without the each loop:

$("tr:not(:has(#1))").remove();

This uses the :has selector to return rows which contain an element matching the selector. It uses the :not selector to get the opposite of that (so you end up with all rows that do not contain an element matching the selector), and then uses remove to remove all elements in the matched set.

Upvotes: 4

Related Questions