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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/906432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:06:04  来源:igfitidea点击:

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

jqueryhtmlhtml-lists

提问by Tanmoy

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

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

回答by Mario Menger

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

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

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

Or using a specific id:

或者使用特定的 id:

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

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

如果您有一个带有 ul 的 jQuery 对象:

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

回答by Samir Talwar

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()

回答by user602668

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

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

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



To remove all items from any list

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

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

回答by cletus

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

回答by user2314737

Here's a way to do it using slice

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