Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    $('[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.

like image 808
ditto Avatar asked Apr 02 '13 08:04

ditto


2 Answers

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();
});
like image 112
novalagung Avatar answered Oct 21 '22 04:10

novalagung


Try:

 $('[id="' + this.id + '"]:not(#" + this.id + ":first)').remove();
like image 32
Mahesh Reddy Avatar answered Oct 21 '22 03:10

Mahesh Reddy