Adam Pietrasiak
Adam Pietrasiak

Reputation: 13204

jQuery select all items with same ID

I know its bad, I know ID is unique and I need to fix it on massive scale on some set of pages.

I dont know what are those ID, I only know class of it, so is it possible to somehow do

$('.someClass').itemsThatHasIdDuplicate().each(function(){
    $(this).attr('id', Math.random()); //its stupid to use random for ID, but shows what I mean
});

ps. I've found this, but this assumes that you know what the ID is.

Upvotes: 1

Views: 15544

Answers (4)

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10153

You have to make sure you don't overwrite the original ID

var cls = 'foo';
$('.' + cls).each(function() {
    var me = this;
    var id = $(me).attr('id');
    var dupes = $('#' + id + '.' + cls);
    dupes.each(function() {
        if(this != me) {
            $(this).attr('id', id + '_r_' + Math.random());
        }
        else {
            $(this).attr('id', id + '_o');
        }
    });
});

This way you also know what the first instance of each ID is.

http://jsfiddle.net/g2DWR/1/

Edit: also, in a plugin form so you can chain it $('.foo').fixDupes().css('color', 'red');

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816580

What you can do is iterate over all elements of that class and group those elements with the same ID. Then modify those groups with more than one element:

var IDs = {};   
var idModifier = function(index, id) {
    return id + index;
};

$('.someClass').each(function() {
    (IDs[this.id] || (IDs[this.id] = [])).push(this);
});

$.each(IDs, function(id, elements) {
    if (elements.length > 1) {
        $(elements).prop('id', idModifier);
    }
});

The "advantage" of this method is that you are searching the document only once, at the beginning with $('.someClass').

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

First of all add some class to all the element having same id.

$('[id]').each(function(){
  var ids = $('[id="'+this.id+'"]');
  if(ids.length>1 && ids[0]==this){
    $('#'+this.id).addClass('changeID');
}
});

and then change the id of all the element having that class...

$('.changeID').each(function(){
$(this).attr("id","changed_"+Math.random());
}

FYI: I would suggest you picking date time for assigning id rather than using math.random()

Upvotes: 0

palaѕн
palaѕн

Reputation: 73916

You can do this using the .attr( attributeName, function(index, attr) ):

// Get all the items with Duplicate id
var $itemsThatHasIdDuplicate = $('[id]').filter(function () {
    return $('[id="' + this.id + '"]').length > 1;
});

// Modify the id for all of them
$itemsThatHasIdDuplicate.attr('id', function (i, val) {
    return 'newID' + (i + 1);
});

Demo: Fiddle

Upvotes: 3

Related Questions