49

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

4

5 回答 5

114

要从页面上的所有 ul-s 中删除既不是第一个也不是最后一个的 li-s:

$('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();
于 2009-05-25T11:51:51.703 回答
18

您是否尝试过选择所有列表元素,然后从列表中删除第一个和最后一个?

$('ul li').not('li:first, li:last').remove()
于 2009-05-25T11:48:10.603 回答
7
$('ul li').not('li:first, li:last').remove(); 

这将从列表中删除所有项目,除了/排除第一个和最后一个元素,


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

$('#yourulid li').remove();  //remove all li items from list named/id #yourulid
于 2011-02-04T05:39:33.943 回答
2
$("ul li:not(:first-child):not(:last-child)").remove();
于 2009-05-25T11:51:51.873 回答
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>

于 2019-01-27T16:13:52.070 回答