jQuery: Finding duplicate ID's and removing all but the first

前端 未结 8 1551
天涯浪人
天涯浪人 2020-12-13 20:57
    $(\'[id]\').each(function () {

        var ids = $(\'[id=\"\' + this.id + \'\"]\');

        // remove duplicate IDs
        if (ids.length > 1 && id         


        
相关标签:
8条回答
  • 2020-12-13 21:23

    try this

    var duplicated = {};
    
    $('[id]').each(function () {   
    
        var ids = $('[id="' + this.id + '"]');
    
        if ( ids.length <= 1 ) return  ;
    
        if ( !duplicated[ this.id ] ){
             duplicated[ this.id ] = [];   
        }       
    
        duplicated[ this.id ].push( this );
    
    });
    
    // remove duplicate last ID, for elems > 1 
    for ( var i in duplicated){
    
        if ( duplicated.hasOwnProperty(i) ){  
    
                 $( duplicated[i].pop() ).remove();            
        }
    }
    

    and jsfiddle is http://jsfiddle.net/z4VYw/5/

    0 讨论(0)
  • 2020-12-13 21:25
    $('[id]').each(function() {
       var $ids = $('[id=' + this.id + ']');
       if ($ids.length > 1) {
         if(this.id === your_id)//which is duplicating
             $ids.not(':first').remove();
         }
    });
    
    0 讨论(0)
  • 2020-12-13 21:27

    Use jquery filter :gt(0) to exclude first element.

    $('[id]').each(function () {
        $('[id="' + this.id + '"]:gt(0)').remove();
    });
    

    Or select all the available elements, then exclude the first element using .slice(1).

    $('[id]').each(function (i) {
        $('[id="' + this.id + '"]').slice(1).remove();
    });
    
    0 讨论(0)
  • 2020-12-13 21:31

    you can try

    $("#ID").nextAll().remove();
    
    0 讨论(0)
  • 2020-12-13 21:33

    Try:

     $('[id="' + this.id + '"]:not(#" + this.id + ":first)').remove();
    
    0 讨论(0)
  • 2020-12-13 21:34

    I'd use not() to remove the current element from ids and remove the rest:

    (Fiddle)

    $('body').on("click", ".placeholder", function() {
    
        data = '<section id="e1"><input name="e1name" /></section><section id="two"><input name="two" value="two section" /></section>';
    
        $('form').append(data);
    
            // ideally I'd like to run this function after append but after googling I find that's not possible.
            // for each ID ...
            $('[id]').each(function () {
    
                var ids = $('[id="' + this.id + '"]');
    
                if (ids.length>1) {                    
                    ids.not(this).remove();            
                }
    
                return;
    
            });
    
    });
    
    0 讨论(0)
提交回复
热议问题