javascript - removing duplicates from html elements - Stack Overflow

what's the best way to remove the grapes duplicate from this? there are tons of ways of removing d

what's the best way to remove the grapes duplicate from this? there are tons of ways of removing duplicates from simple arrays, but this would be an array with html elements

 <div class="fruit">
      grapes
 </div>
 <div class="fruit">
      bananas
 </div>
 <div class="fruit">
      grapes
  </div>

I've tried using something like

 $('.fruit').each(function () {
      $('.fruit:has("' + $(this).text() + '"):gt(0)').remove();  
 });

what's the best way to remove the grapes duplicate from this? there are tons of ways of removing duplicates from simple arrays, but this would be an array with html elements

 <div class="fruit">
      grapes
 </div>
 <div class="fruit">
      bananas
 </div>
 <div class="fruit">
      grapes
  </div>

I've tried using something like

 $('.fruit').each(function () {
      $('.fruit:has("' + $(this).text() + '"):gt(0)').remove();  
 });
Share Improve this question asked Aug 7, 2013 at 6:37 archytectarchytect 3,7255 gold badges25 silver badges31 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 3

Try

var obj = {};
$('.fruit').each(function(){
    var text = $.trim($(this).text());
    if(obj[text]){
        $(this).remove();
    } else {
        obj[text] = true;
    }
})

Demo: Fiddle

:has expects an element selector while :contains takes a string

see http://api.jquery./contains-selector/

so this should do the trick:

 $('.fruit').each(function () {
      $('.fruit:contains("' + $(this).text() + '"):gt(0)').remove();  
 });

fiddle: http://jsfiddle/kam7E/

http://jsfiddle/S3wXM/1/

Assuming that you wish to remove only one of the duplicates.

Using contains, like the answer above but implementation is slightly different.

$($("div:contains('grapes')")[0]).remove();

http://api.jquery./jQuery.unique/ - This also might be of use to you.

var uniqueFruits = [];
$(".fruit").each(function(i,e){
    var thisFruit = $.trim($(e).text());
    if(uniqueFruits.indexOf(thisFruit) == -1)
        uniqueFruits.push(thisFruit);
    else
        $(e).remove();
});

http://jsfiddle/a7E9e/

jsFiddle here: http://jsfiddle/THEtheChad/UKRwf/

var found = {};
var $unique_fruits = $('.fruit').filter(function(){
   var data = this.innerHTML.trim();

   if(!found.hasOwnProperty(data)) return found[data] = true;
});

Here is the working fiddle for this:-

http://jsfiddle/HwUUs/1/

$( "div:contains('grapes')" ).remove();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744118868a4559304.html

相关推荐

  • javascript - removing duplicates from html elements - Stack Overflow

    what's the best way to remove the grapes duplicate from this? there are tons of ways of removing d

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信