jquery删除除第一个之外的所有元素

Hul*_*ulk 60 jquery

使用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>
';
Run Code Online (Sandbox Code Playgroud)

hsz*_*hsz 97

试试:

$(html).not(':first').remove();
Run Code Online (Sandbox Code Playgroud)

或者更具体:

$(html).not('span:first').remove();
Run Code Online (Sandbox Code Playgroud)

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

$('#addin .engagement_data:last-child .keys_values').not('span:first').remove();
Run Code Online (Sandbox Code Playgroud)


Nig*_*gel 40

或者,作为替代方案:

$('span').slice(1).remove();
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

  • 如果你想保持超过1,这很有用.保持3:$('span').slice(3).remove(); (3认同)

luk*_*nis 10

使用此选择器:

$('span:not(first-child)')
Run Code Online (Sandbox Code Playgroud)

所以你的代码是这样的:

$('span:not(first-child)').remove();
Run Code Online (Sandbox Code Playgroud)


小智 7

以下代码对我有用:

$(html).children().not(':first').remove();
Run Code Online (Sandbox Code Playgroud)


Has*_*dar 6

试试这个

$('html').not(':first').remove();
Run Code Online (Sandbox Code Playgroud)


Jef*_*ery 5

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

<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>
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)