tags:

views:

1137

answers:

3

I have the ul. Now I have to remove all the li elements inside it except first and last li. How can I do it through JQuery. Tried remove method but could not find a way.

+5  A: 

Have you tried selecting all the list elements, and then removing the first and last ones from the list?

$('ul li').not('li:first, li:last').remove()
Samir Talwar
+5  A: 

To remove from all ul-s on the page the li-s that are neither the first nor the last:

$('ul li:not(:first):not(:last)').remove();

Or using a specific id:

$('#yourul li:not(:first):not(:last)').remove();

If you have a jQuery object with your ul in it:

$(yourul).find('li:not(:first):not(:last)').remove();
Mario Menger
I forgot you could chain :not selectors like that. Nice one.
Samir Talwar
A: 
$("ul li:not(:first-child):not(:last-child)").remove();
cletus
Wouldn't that remove the ul?
Mario Menger