如何删除UL内的所有li元素,除了第一和使用jQuery的最后一个要素是什么?
-
05-09-2019 - |
题
我有一个<ul>
元件。怎样才能去除所有的<li>
元件里面,除了第一个和最后,使用jQuery?
解决方案
要从所有UL-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();
其他提示
您是否尝试过所有的选择列表元素,然后从列表中删除第一个和最后的?
$('ul li').not('li:first, li:last').remove()
$('ul li').not('li:first, li:last').remove();
此将从列表中的删除所有项目除了/排除强>第一和最后一个元素,
要从任何列表中删除所有项目
$('#yourulid li').remove(); //remove all li items from list named/id #yourulid
$("ul li:not(:first-child):not(:last-child)").remove();
下面是一个使用的方式来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>
不隶属于 StackOverflow