Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
348 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...