jQuery删除除第一个元素外的所有元素


73

使用jquery删除如何删除除第一个之外的所有span标签。

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>
';

Answers:


107

尝试:

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

或更具体地说:

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

要将其从DOM而不是html变量中删除,请使用选择器:

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

这将从html元素中删除跨度。如何从DOM中删除跨度。请查看编辑
Hulk

1
我尝试了您的最后一个陈述,似乎所有的span元素都被删除
绿巨人

如果您$('#addin .engagement_data:last-child .keys_values')返回两个span元素,它应该可以正常工作。您确定它返回的只是没有父母的跨度吗?
hsz 2013年

1
是的,它只是返回span,这对我有用。.$('#addin .engagement_data:last-child .keys_values')。find(“ span:gt(0)”)。remove();
绿巨人

46

或者,作为替代:

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

slice()
给定一个表示一组DOM元素的jQuery对象,.slice()方法构造一个新的jQuery对象,其中包含由start和(可选)end参数指定的元素的子集。

start
类型:Integer
一个整数,指示从0开始的位置,在该位置开始选择元素。如果为负,则表示距集合末端的偏移量。

资料来源:https : //api.jquery.com/slice

因此,$('span').slice(1).remove()将选择并删除第一个实例之后的所有元素。


6
如果您想保留1个以上,这将很有用。保留3:$('span')。slice(3).remove();
Alex R.

11

使用此选择器:

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

所以你的代码是这样的:

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


6

当您在内容中除了要查找的类型的子元素之外没有其他内容时,以上内容可能适用于特定示例。但是您会遇到标记更复杂的问题:

<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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.