[英]jquery remove all elements except for first one
使用 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 對象,其中包含由 start 和可選的 end 參數指定的元素的子集。開始
類型:整數
一個整數,指示開始選擇元素的從 0 開始的位置。 如果為負,則表示與集合末尾的偏移量。
來源: https : //api.jquery.com/slice
因此, $('span').slice(1).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
以下代碼對我有用:
$(html).children().not(':first').remove();
該代碼是正確的
$('.screenshot-items .slider-item').not(':first').remove();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.