How to remove all li elements inside an ul except the first and the last elements using jQuery?

Tanmoy picture Tanmoy · May 25, 2009 · Viewed 59.3k times · Source

I have a <ul> element. How can remove all the <li> elements inside it, except for the first and the last, using jQuery?

Answer

Mario Menger picture Mario Menger · May 25, 2009

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

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

Or using a specific id:

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

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

$(yourul).find('li:not(:first-child):not(:last-child)').remove();