removing duplicates from html elements

前端 未结 6 1828
野趣味
野趣味 2020-12-21 17:49

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 element

相关标签:
6条回答
  • 2020-12-21 18:16

    Here is the working fiddle for this:-

    http://jsfiddle.net/HwUUs/1/

    $( "div:contains('grapes')" ).remove();
    
    0 讨论(0)
  • 2020-12-21 18:24

    http://jsfiddle.net/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.com/jQuery.unique/ - This also might be of use to you.

    0 讨论(0)
  • 2020-12-21 18:25

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

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

    so this should do the trick:

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

    fiddle: http://jsfiddle.net/kam7E/

    0 讨论(0)
  • 2020-12-21 18:28

    Try

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

    Demo: Fiddle

    0 讨论(0)
  • 2020-12-21 18:35
    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.net/a7E9e/

    0 讨论(0)
  • 2020-12-21 18:36

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

    var found = {};
    var $unique_fruits = $('.fruit').filter(function(){
       var data = this.innerHTML.trim();
    
       if(!found.hasOwnProperty(data)) return found[data] = true;
    });
    
    0 讨论(0)
提交回复
热议问题