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

9

16
    $('[id]').each(function () {

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

        // remove duplicate IDs
        if (ids.length > 1 && ids[0] == this) $('#' + this.id).remove();

    });

The above will remove the first duplicate ID, however I want to remove the last. I've tried $('#'+ this.id + ':last') but to no avail.

Fiddle

In the fiddle the input with the value 'sample' should be kept when the append action takes place.

Placenta answered 2/4, 2013 at 8:53 Comment(0)
D
26

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();
});
Donothing answered 2/4, 2013 at 9:4 Comment(5)
$(this).attr('id') === this.idCirculate
rather than repeating the selector with :gt(0) you could just use ids.slice(1) to get everything except the 0th element in idsCirculate
I want delete last element.. For that what should I do??Pinta
I tried $('.product').slice(0).remove(); it is deleting all productsPinta
$('.product:not(:last-child)').slice(0).remove(); @DeviA This will remove all except the last child.Balduin
H
4

Try:

 $('[id="' + this.id + '"]:not(#" + this.id + ":first)').remove();
Heliometer answered 2/4, 2013 at 9:3 Comment(0)
B
3

you can try

$("#ID").nextAll().remove();
Bradley answered 2/4, 2013 at 9:14 Comment(1)
he can try, but it won't work. It'll remove every following sibling of #id regardless of what element or ID they have.Circulate
T
2
$('[id]').each(function() {
   var $ids = $('[id=' + this.id + ']');
   if ($ids.length > 1) {
     if(this.id === your_id)//which is duplicating
         $ids.not(':first').remove();
     }
});
Theatrics answered 18/8, 2015 at 10:39 Comment(3)
Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem.Canonicity
it will remove the duplicate ids leaving the first one ,it is helpful to remove duplicate ids.............Theatrics
it'll remove all duplicate ids except the first oneTheatrics
R
1

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/

Refrigerant answered 2/4, 2013 at 9:13 Comment(1)
pop will only return one element.Circulate
C
1

This code is longer than some of the others, but the double-nested loop should make its operation obvious.

The advantage of this approach is that it only has to scan the DOM to generate the list of elements with an id attribute once, and then uses the same list to find (and remove) the duplicates.

Elements that were already removed will have parentNode === null so can be skipped while iterating over the array.

var $elems = $('[id]');
var n = $elems.length;

for (var i = 0; i < n; ++i) {
    var el = $elems[i];
    if (el.parentNode) {  // ignore elements that aren't in the DOM any more
        var id = el.id;
        for (var j = i + 1; j < n; ++j) {
            var cmp = $elems[j];
            if (cmp.parentNode && (cmp.id === id)) {
                $(cmp).remove();  // use jQuery to ensure data/events are unbound
            }
        }
    }
}
Circulate answered 2/4, 2013 at 9:27 Comment(0)
G
0

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;

        });

});
Gastronome answered 2/4, 2013 at 9:6 Comment(0)
E
0

Try Using The below function Works fine for me:

 $('#favourities-ajax ul li').each(function(i) {
      $('[id="' + this.id + '"]').slice(1).remove();
      });
Evocative answered 22/8, 2017 at 7:5 Comment(0)
B
0
//This will remove all except the last child.
$('#my_id:not(:last-child)').slice(0).remove();

//This will remove all except the first child.
$('#my_id').slice(1).remove();
Balduin answered 3/1, 2023 at 3:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.