jQuery remove duplicated div with class name

后端 未结 3 1340

So basically my div generates like this:

content
content
<
3条回答
  •  滥情空心
    2021-01-05 09:16

    ORIGINAL (See edit below)

    As Jan Dvorak has asked, I'm not sure which properties you believe determine that an element is a duplication of another, however, the following is a not particularly quick but more generic solution to your problem:

    (function($) {
      $.fn.removeDuplicates = function() {
        var original = [];
    
        this.each(function() {
          var el = this, $el, isDuplicate;
    
          $.each(original, function() {
            $el = $(el);
    
            // check whichever properties 
            // you believe determine whether 
            // it's a duplicate or not
            if (el.tagName === this.tagName && 
                el.className === this.className && 
                el.id === this.id && 
                el.value === this.value && 
                el.href === this.href && 
                $el.html() === $(this).html()) {
              isDuplicate = true;
              $el.remove();
            }
          });
    
          if (!isDuplicate) {
            original.push(el);
          }
        });
      };
    }(jQuery));
    

    You would use it like this:

    $('.test').removeDuplicates();
    
    // .. or even
    $('div').removeDuplicates();
    
    // .. or even
    $('.test.className').removeDuplicates();
    

    All of the above should work as expected, as demonstrated here.

    EDIT

    It's been a few years since I wrote this and I have since learnt of Node.isEqualNode. It gives a much cleaner way to do this so the updated plugin would look like the following (and would return the original element to chain against):

    (function($) {
      'use strict';
    
      $.fn.removeDuplicates = function() {
        var $original = $([]);
    
        this.each(function(i, el) {
          var $el = $(el),
              isDuplicate;
    
          $original.each(function(i, orig) {
            if (el.isEqualNode(orig)) {
              isDuplicate = true;
              $el.remove();
            }
          });
    
          if (!isDuplicate) {
            $original = $original.add($el);
          }
        });
    
        return $original;
      };
    
    }(jQuery));
    

    A working example is demonstrated here.

提交回复
热议问题