jQuery를 사용하여 첫 번째와 마지막 요소를 제외한 UL 내부의 모든 Li 요소를 제거하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/906432

  •  05-09-2019
  •  | 
  •  

문제

나는있다 <ul> 요소. 모든 것을 제거 할 수있는 방법 <li> jQuery를 사용하는 첫 번째와 마지막을 제외하고 그 안에 요소가 있습니까?

도움이 되었습니까?

해결책

페이지의 모든 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();

다른 팁

모든 목록 요소를 선택한 다음 목록에서 첫 번째 및 마지막 요소를 제거한 적이 있습니까?

$('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>

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top