Design & Download
Your JS Library
in Seconds!!!

Snippet: ids() - Unique Element IDs

Written by Christopher West (cwest) on March 30, 2016.
Get unique element IDs for starting with whatever prefix(es) you want.
function ids(ids, opt_document) {
  opt_document = opt_document || document;
  var suffix, i, l = (ids = typeOf(ids, 'Array') ? ids : [ids]).length, ret = [];
  ret.input = ids;
  do {
    ret.suffix = suffix = ('_' + Math.random()).replace('0.', '');
    for (i = 0; i < l && !opt_document.getElementById(ret[i] = ids[i] + suffix); i++);
  } while (i < l);
  return ret;
}

ids() API Documentation

Description

Get unique element IDs starting with whatever prefix(es) you want.

Parameters

  1. ids {string|Array.<string>}:
    The prefix(es) to be appended to.
  2. opt_document {Document}:
    Optional. Defaults to the document in which YourJS is defined. The document whose elements will be checked to make sure that none of them have the returned IDs.

Returns

Returns an array containing the modified ID(s). Each ID will end in a suffix of an underscore followed by a random number. The .suffix property of the returned array will contain the suffix appended to all of the contained IDs. The .input property of the returned array will contain the array of IDs to which the suffix was appended.