javascript - jquery 删除元素,如果它出现两次

标签 javascript jquery html

我的 html 中有这样的内容:

<div class="onlyContent">
    <!-- some more stuff here -->
</div>
<div class="onlyContent">
    <!-- some more stuff here -->
</div>

现在,使用 jQuery 我想从 dom 中删除第二次出现的 onlyContent HTML 类。

最终结果应该是这样的:

<div class="onlyContent">
    <!-- some more stuff here -->
</div>

我发现你可以以某种方式使用nth-child选择器,但尝试以这种方式访问​​它并没有为我做到

$('.onlyContent:nth-child(2)').remove(); 

最佳答案

您可以使用 :eq(1) 来定位匹配集中的第二个元素:

$('.onlyContent:eq(1)').remove(); 

如果元素数量超过两个,则应使用 :not(:first):gt(0):

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

$('.onlyContent:gt(0)').remove(); 

关于javascript - jquery 删除元素,如果它出现两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30371831/

相关文章:

javascript - 选择要循环的数组

javascript - 安装 web3 出现以太坊错误

html - 将 div 的高度设置为 70%

javascript - HTML5 拖放抛出未定义不是函数错误

javascript - Laravel 5 js 被 app.js 阻塞

javascript - 具有重力的2D碰撞检测-JavaScript

javascript - 项目的切换类 Vue.js

javascript - 无法使用javascript获取输入字段值?

javascript - 当页面保存在 DOM 中时,如何使用开/关在 Jquery-Mobile 中正确解除绑定(bind)事件?

javascript - innerHTML 在 Firefox 中无法正常工作?