Unique ID Generator

In preparation for an article on building and traversing node trees, I realized that I had not yet written an article covering a method to generate unique IDs, which is needed to provide a unique identifier for each node. We need a method that generates a unique string and does not repeat any ids. In addition, there should be an optional parameter to check that the ID does not yet exist in the DOM. Here is the method:

Example 1: Unique ID Generator

var MES_UNIQUE_IDS = {};

var mes_generateUniqueId = function(charset, len, isNotInDOM) {
    var i = 0;
    if (! charset) {charset = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;}
    if (! len) {len = 8;}
    var id = , charsetlen = charset.length, charIndex;

    // iterate on the length and get a random character for each position
    for (i = 0; len > i; i += 1) {
        charIndex = Math.random() * charsetlen;
        id += charset.charAt(charIndex);

    if (MES_UNIQUE_IDS[id] || (isNotInDOM && YAHOO.util.Dom.get(id))) {
		MES_UNIQUE_IDS[id] = true; // add DOM ids to the map
        return mes_generateUniqueId(charset, len, isNotInDOM);
    MES_UNIQUE_IDS[id] = true;

    return id;

First, setup a global object MES_UNIQUE_IDS to be used to keep track of which IDs have already been generated by the function. The function mes_generateUniqueId takes up to 3 optional parameters: a charset string containing the characters used to generate your unique string (defaults to all upper- and lower-case latin characters and numbers), a length (len) for the IDs to be (default is 8), and isNotInDOM governs whether to check if the generated ID exists in the DOM. The for loop randomly chooses a character from the character set and appends it to the ID, up to the provided length. Then, if the ID already existed, or isNotInDOM is true and the ID is in the DOM, we recursively call mes_generateUniqueId until a unique ID is returned. Lastly, the ID is added to the unique ID object, so that it is never reused (until the page is refreshed).

One caveat of this function is when the charset or len are too small, then it is possible that all unique IDs are used up and mes_generateUniqueId will cause too much recursion. Most browsers will automatically handle this and stop executing, but it would be best to use a charset of at least 4 different characters, and a len of 4 or more. However, the default setting will support up to 839299365868340224 unique combinations.

If you want to clear the unqiue IDs, simply delete MES_UNIQUE_IDS and reset it to an empty object. Also, check out the Unique ID Generator Test Page for a practical example.