CodeOverload
CodeOverload

Reputation: 48485

jQuery code to delete all spans with same content but keep one

Say i have the following html:

<span class="fruit">Apple</span>
<span class="fruit">banana</span>
<span class="fruit">Apple</span>
<span class="fruit">Apple</span>
<span class="fruit">orange</span>

I tried different methods but it didn't work, I want a jQuery code to remove all (.fruit) spans with same content but keep one (the first if possible), so i will end up with the following:

<span class="fruit">Apple</span>
<span class="fruit">banana</span>
<span class="fruit">orange</span>

Thank you

Upvotes: 3

Views: 927

Answers (4)

thethanghn
thethanghn

Reputation: 329

temp = $('span:first').clone(true);
//remove all the span
$().html();
$().append(temp);

Upvotes: 0

Lee
Lee

Reputation: 1662

$('span.fruit').each(function(){
  return $('span.fruit:contains('+$(this).text()+'):not(:first)').remove();
})

Upvotes: 2

Peeter
Peeter

Reputation: 9382

var temp = array[];

$(".fruit").each(function(i) {
    var html = $($this).html();
    if($.inArray(html, temp)) {
        $($this).remove();
    }
    else {
        temp.push(html);
    }

});

Upvotes: 1

David Morton
David Morton

Reputation: 16505

 $("span.fruit:contains(Apple):not(:first)").remove();

Upvotes: 8

Related Questions