最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - removing duplicates from html elements - Stack Overflow

programmeradmin9浏览0评论

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();
发布评论

评论列表(0)

  1. 暂无评论