最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery remove element if it occurs twice - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

7 Answers 7

Reset to default 6

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

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();
发布评论

评论列表(0)

  1. 暂无评论