To select and remove all elements except the first one, you can utilize the :nth-child
pseudo-class selector.
$('.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>
You can also achieve this by combining the :first-child
and :not()
pseudo-class selectors.
$('.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>
Note: To initially hide the elements, you can apply the following CSS.
.valid:nth-child(n+2){
display : none;
}
If you prefer not to use the jQuery library, you can achieve the same result using pure JavaScript.
// get all duplicate element and convert NodeList into an array
// use [].slice.call in older browsers to convert it to an array
Array.from(document.querySelectorAll('.valid:nth-child(n+2)'))
// iterate over elements
.forEach(function(element) {
// remove element from its parent
element.parentNode.removeChild(element);
});
<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>