Wang'l Pakhrin
Wang'l Pakhrin

Reputation: 868

Remove all child elements from table except for first?

My HTML:

<table id="user-table">
      <tr><td>1</td></tr>
      <tr><td>2</td></tr>
      <tr><td>3</td></tr>     
</table>

How can I remove all child elements of the user-table except the first <tr> using jQuery?

What I've tried:

$("#user-table").children().remove();

However it removes all the child <tr> elements but I want the first row not to be removed.

Here's my jQuery so far:

$('#add-form').submit(function(e) {
    e.preventDefault();
    $.post("../lib/ajax/add-user.php", $("#add-form").serialize(),
    function(data){ 
    javascript:jQuery.fancybox.close();

    $("#user-table").children().remove();
    //$('#list-box').fadeTo(800,1,function(){

    //$(this).empty();
    //$(this)..append(data);                            

    //});
});

Upvotes: 6

Views: 13435

Answers (3)

Jeetendra
Jeetendra

Reputation: 205

I once was also on the same problem and I fixed using:

$('#user-table > tr:not(:first)').remove();

you will also be done.

Upvotes: 2

dsgriffin
dsgriffin

Reputation: 68596

slice() is by far the fastest way you're going to be able to do this:

$('#user-table tr').slice(1).remove();

jsFiddle here.

Upvotes: 17

Adil Shaikh
Adil Shaikh

Reputation: 44740

You can do this -

$('#parentDiv > div:gt(0)').remove();

Demo ---> http://jsfiddle.net/aaCam/

Upvotes: 2

Related Questions