jquery remove element if it occurs twice

六月ゝ 毕业季﹏ 提交于 2021-01-29 08:05:03

问题


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(); 

回答1:


You 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(); 



回答2:


use below code . use jQuery :eq() selector.

Select the element at index n within the matched set.

check DEMO

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



回答3:


you can try this

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



回答4:


You can try this -

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

It will remove all the duplicates. Only the first one will be present.




回答5:


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.




回答6:


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();
}



回答7:


you can try

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


来源:https://stackoverflow.com/questions/30371831/jquery-remove-element-if-it-occurs-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!