从DOM中删除重复的元素

时间:2018-06-27 04:47:15

标签: jquery html css

要从DOM中删除具有相同类名(有效)的重复元素。下面是示例:

<div class="content">
<div class="test1">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
</div>  
<div class="test2">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
</div>
</div>

预期是:

<div class="content">
<div class="test1">
    <label class="valid">&nbsp;</label>
</div>  
<div class="test2">
    <label class="valid">&nbsp;</label>
</div>
</div>

1 个答案:

答案 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">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
</div>  
<div class="test2">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</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">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
</div>  
<div class="test2">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</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">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
  </div>
  <div class="test2">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
  </div>
</div>