我有一个 <ul>
元素。如何使用jQuery删除其中所有的 <li>
元素,但保留第一个和最后一个元素?
我有一个 <ul>
元素。如何使用jQuery删除其中所有的 <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();
你尝试过选择所有列表元素,然后从列表中移除第一个和最后一个元素吗?
$('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>