admin管理员组文章数量:1326332
I have something like this in my html:
<div class="onlyContent">
<!-- some more stuff here -->
</div>
<div class="onlyContent">
<!-- some more stuff here -->
</div>
Now, with jQuery
I want to remove the 2nd occurence of the class onlyContent
HTML from the dom.
The final result should be this:
<div class="onlyContent">
<!-- some more stuff here -->
</div>
I figured out that you can somehow use the nth-child
-selector, but trying to access it this way didn't do it for me
$('.onlyContent:nth-child(2)').remove();
I have something like this in my html:
<div class="onlyContent">
<!-- some more stuff here -->
</div>
<div class="onlyContent">
<!-- some more stuff here -->
</div>
Now, with jQuery
I want to remove the 2nd occurence of the class onlyContent
HTML from the dom.
The final result should be this:
<div class="onlyContent">
<!-- some more stuff here -->
</div>
I figured out that you can somehow use the nth-child
-selector, but trying to access it this way didn't do it for me
$('.onlyContent:nth-child(2)').remove();
Share
Improve this question
asked May 21, 2015 at 11:02
DasSaffeDasSaffe
2,1981 gold badge31 silver badges74 bronze badges
1
- you code is working Demo – ozil Commented May 21, 2015 at 11:06
7 Answers
Reset to default 6You can use :eq(1)
for targetting second element in matched set:
$('.onlyContent:eq(1)').remove();
If the number of elements more than two, then you should use :not(:first)
or :gt(0)
:
$('.onlyContent:not(:first)').remove();
or
$('.onlyContent:gt(0)').remove();
use below code . use jQuery :eq() selector.
Select the element at index n within the matched set.
check DEMO
$('.onlyContent:eq(1)').remove();
you can try this
$('.onlyContent:gt(0)').remove();
You can try this -
$('.onlyContent:gt(0)').remove();
It will remove all the duplicates. Only the first one will be present.
You can use .slice
for this.
$(".onlyContent").slice(1).remove();
Nice and simple, no fuss. Working example.
From the .slice
documentation:
Reduce the set of matched elements to a subset specified by a range of indices
You can find more here.
Use .length property to check the numbers of selected elements on the page and if its value is greater than 1 then remove the elements other than first...
if($('.onlyContent').length > 1) {
$('.onlyContent:gt(0)').remove();
}
you can try
$(".onlyContent").not(':first').remove();
本文标签: javascriptjquery remove element if it occurs twiceStack Overflow
版权声明:本文标题:javascript - jquery remove element if it occurs twice - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742200304a2431804.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论