如何使用jQuery删除ul中除第一个和最后一个元素之外的所有li元素?

49

我有一个 <ul> 元素。如何使用jQuery删除其中所有的 <li> 元素,但保留第一个和最后一个元素?

5个回答

115
从页面上所有的ul中删除既不是第一个也不是最后一个li元素:
$('ul li:not(:first-child):not(:last-child)').remove();

或者使用特定的id:

$('#yourul li:not(:first-child):not(:last-child)').remove();
如果您有一个包含ul元素的jQuery对象:
$(yourul).find('li:not(:first-child):not(:last-child)').remove();

18

你尝试过选择所有列表元素,然后从列表中移除第一个和最后一个元素吗?

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

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

这将从列表中删除除第一个和最后一个元素以外的所有项


要从任何列表中删除所有项目

$('#yourulid li').remove();  //remove all li items from list named/id #yourulid

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

0
这是一种使用 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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接