Vasileios Vasileios - 2 months ago 14
jQuery Question

jQuery: Check if an element with the same attribute exists more than once

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


My approach in jQuery:

$('.list').each(function(){

if ( $(this).attr(data-productid).length > 0 ) {

$(this).remove();


}

});


Any ideas guys,

Thank you!

Answer

You could remove any dupe which isn't the first one:

$('.list').each(function(){
   $('[data-productid='+$(this).data('productid')+']:not(:first)').remove();
});

-DEMO-