Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 920
Tanmoy Avatar asked May 25 '09 11:05

Tanmoy


People also ask

How do I delete all Li in UL?

To remove all li elements from a ul element with JavaScript, we can set the innerHTML property of the ul element to an empty string. Then we write: document. getElementById("root").

Does Li have to be inside UL?

The HTML <li> element is used to represent an item in a list. It must be contained in a parent element: an ordered list ( <ol> ), an unordered list ( <ul> ), or a menu ( <menu> ). So yes, you need to nest any <li> element inside a list or menu. However a <li> element may contain nearly every other element inside.


1 Answers

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(); 
like image 191
Mario Menger Avatar answered Sep 21 '22 05:09

Mario Menger