Since identifiers must be guaranteed to be unqiue, but not necessarily random, it is much better to just use a monotonically increasing identification number with an alpha prefix like this:
function assignID(elem, prefix) { prefix = prefix || "autoId_"; if (elem.id) { return (elem.id); } else { if (!assignID.cntr) { assignID.cntr = 1; } var id = prefix + assignID.cntr++; elem.id = id; return(id); } }
This uses the function property assignID.cntr to keep track of the counter, which increments it every time it is used, so the identifiers assigned here will never be the same as the previously assigned identifier.
Then you can make sure that any element always has an id by simply doing this:
assignID(elem, "plot");
If you need a jQuery method that does this, you can do it this way:
jQuery.assignIDCntr = 1; jQuery.fn.assignID = function(prefix) { prefix = prefix || "autoId_"; return this.each(function() { if (!this.id) { this.id = prefix + jQuery.assignIDCntr++; } }); }
And then you will use it as follows:
$(".myobjects").assignID("plot");
source share