要从DOM中删除具有相同类名(有效)的重复元素。下面是示例:
<div class="content">
<div class="test1">
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
</div>
<div class="test2">
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
</div>
</div>
预期是:
<div class="content">
<div class="test1">
<label class="valid"> </label>
</div>
<div class="test2">
<label class="valid"> </label>
</div>
</div>
答案 0 :(得分:3)
使用:nth-child
伪类选择器选择除第一个元素以外的所有元素,然后将其删除。
$('.valid:nth-child(n+2)').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<div class="test1">
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
</div>
<div class="test2">
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
</div>
</div>
或结合使用:first-child
和:not()
伪类选择器。
$('.valid:not(:first-child)').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<div class="test1">
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
</div>
<div class="test2">
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
</div>
</div>
仅供参考::要最初隐藏元素,可以使用以下CSS。
.valid:nth-child(n+2){
display : none;
}
不使用jQuery库。
// get all duplicate element and convert nodelinst into array
// use [].slice.call in older browser to convert in to an array
Array.from(document.querySelectorAll('.valid:nth-child(n+2)'))
// iterate over elements
.forEach(function(ele) {
// remove element from its parent
ele.parentNode.removeChild(ele);
});
<div class="content">
<div class="test1">
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
</div>
<div class="test2">
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
<label class="valid"> </label>
</div>
</div>