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

5

51

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

Footway answered 25/5, 2009 at 11:44 Comment(0)
A
116

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();
Astrict answered 25/5, 2009 at 11:51 Comment(0)
E
18

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()
Etrem answered 25/5, 2009 at 11:48 Comment(0)
P
7
$('ul li').not('li:first, li:last').remove(); 

This will remove all items from list Except/Exclude first and last element,


To remove all items from any list

$('#yourulid li').remove();  //remove all li items from list named/id #yourulid
Pious answered 4/2, 2011 at 5:39 Comment(0)
R
2
$("ul li:not(:first-child):not(:last-child)").remove();
Reitman answered 25/5, 2009 at 11:51 Comment(0)
P
1

Here's a way to do it using slice

$("#removeAllButFirstAndLast").click(function() {
  $("#myUL").children().slice(1, -1).remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="myUL">
  <li>first</li>
  <li>second</li>
  <li>third</li>
  <li>fourth</li>
</ul>

<div id="removeAllButFirstAndLast">click to remove all but first and last</div>
Palaeography answered 27/1, 2019 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.