user3577990 user3577990 - 1 month ago 8
CSS Question

remove all items except one of each class with jquery

I have a div that contains some items like that

<code>
<pre>
<div class="multiSel">
<span class="KNet" title="KNet">KNet</span>
<span class="Visa" title="Visa">Visa</span>
<span class="KNet" title="KNet">KNet</span>
<span class="Visa" title="Visa">Visa</span>
</div>
</pre>
</code>


I want keep the first item of each class and remove others

Answer

Use :not() selector along with :first selector.

$('.KNet:not(:first),.Visa:not(:first)').remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code>
  <pre>
    <div class="multiSel">
      <span class="KNet" title="KNet">KNet</span>
      <span class="Visa" title="Visa">Visa</span>
      <span class="KNet" title="KNet">KNet</span>
      <span class="Visa" title="Visa">Visa</span>
    </div>
  </pre>
</code>

UPDATE : If all span elements has only single class name then you can do something like this using filter() method.

//$('.KNet:not(:first),.Visa:not(:first)').remove();

$('.multiSel span').filter(function() {
  return $(this).is(':not(.' + this.className + ':first)')
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code>
  <pre>
    <div class="multiSel">
      <span class="KNet" title="KNet">KNet</span>
      <span class="Visa" title="Visa">Visa</span>
      <span class="KNet" title="KNet">KNet</span>
      <span class="Visa" title="Visa">Visa</span>
    </div>
  </pre>
</code>