问题
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