programing

jquery는 첫번째 요소를 제외한 모든 요소를 제거합니다.

cafebook 2023. 10. 20. 14:21
반응형

jquery는 첫번째 요소를 제외한 모든 요소를 제거합니다.

jquery remove를 사용하여 처음의 스팬 태그를 제외한 모든 스팬 태그를 제거하는 방법은 무엇입니까?

EDIT

 var html = var htm = $("#addin").find(".engagement_data:last-child").find(".keys_values").html();
    html='
       <span style="display:block;" class="k_v">
         <innput type="text" class="e_keys" style="width:65px;" placeholder="key"/>
         <input type="text" class="e_values" style="width:65px;" placeholder="value"/>
       </span>
       <span style="display:block;" class="k_v">
         <input type="text" class="e_keys" style="width:65px;" placeholder="key"/>
         <input type="text" class="e_values" style="width:65px;" placeholder="value"/>
       </span>
';

사용해 보기:

$(html).not(':first').remove();

또는 보다 구체적으로 설명하자면:

$(html).not('span:first').remove();

대신 DOM에서 제거하려면html변수 선택기를 사용합니다.

$('#addin .engagement_data:last-child .keys_values').not('span:first').remove();

또는 대안으로:

$('span').slice(1).remove();

썰다
DOM 요소 집합을 나타내는 jQuery 개체가 주어지면 .slice() 메서드는 시작 및 선택적으로 종료 인수에 의해 지정된 요소의 하위 집합을 포함하는 새 jQuery 개체를 구성합니다.

시작하는
유형: 정수
요소가 선택되기 시작하는 0 기반 위치를 나타내는 정수입니다.음이면 집합의 끝에서 오프셋을 나타냅니다.

출처 : https://api.jquery.com/slice

그러므로,$('span').slice(1).remove()는 첫 번째 인스턴스 이후의 모든 요소를 선택하고 제거합니다.

다음 코드가 저에게 적합합니다.

$(html).children().not(':first').remove();

다음 셀렉터를 사용합니다.

$('span:not(first-child)')

그래서 당신의 코드는 다음과 같습니다.

$('span:not(first-child)').remove();

이거 먹어봐요.

$('html').not(':first').remove();

위의 내용은 사용자가 찾고자 하는 유형의 하위 요소를 제외한 다른 내용이 없을 때 특정 예제에 적용될 수 있습니다.그러나 보다 복잡한 마크업으로 인해 문제가 발생하게 됩니다.

<ul id="ul-id" class="f-dropdown tiny" data-dropdown-content="">
    <li>
    <div id="warningGradientOuterBarG" class="barberpole">
    <div id="warningGradientFrontBarG" class="warningGradientAnimationG">
        <div class="warningGradientBarLineG"></div>
    </div>
    </div>
    </li>
    <li>foo</li>
    <li>bar</li>
</ul>

var $ul = $('#ul-id')
$ul.not(':first')  //returns nothing
$ul.find(':first') // returns first <li>
$ul.find(':not(:first)') //returns the inner divs as well as the last two li's
$('#ul-id li:not(first-child)')  // this returns all li's
$('#ul-id li:not(:first)')  // this works: returns last two li's
$ul.find('li').slice(1) // this also works and returns the last two li's
$ul.find('li').slice(1).remove()   // and this will remove them

언급URL : https://stackoverflow.com/questions/18874298/jquery-remove-all-elements-except-for-first-one

반응형