I would like to check if an element with the same data attribute exists more than once in a jQuery each loop and if exists more than once remove it and keep only one element with this data attribute.
I tried this code but doesnt seems to work,
HTML:
<div class="list" data-productid="2"></div> // KEEP THIS ONE
<div class="list" data-productid="3"></div>
<div class="list" data-productid="2"></div> // REMOVE THIS ONE
<div class="list" data-productid="2"></div> // REMOVE THIS ONE
$('.list').each(function(){
if ( $(this).attr(data-productid).length > 0 ) {
$(this).remove();
}
});
You could remove any dupe which isn't the first one:
$('.list').each(function(){
$('[data-productid='+$(this).data('productid')+']:not(:first)').remove();
});