Generating element IDs with JavaScript and counters

The code that I posted in my previous post on creating a unique ID in JavaScript is fairly similar to code that's all over the internet and seemed like it should work. And to be fair, it did work, although with one major problem. If the code runs too quickly it's possible for two elements to have the same "unique" id.

What I came up with instead was using a counter to keep track of the last ID given and increment it each time.

JavaScript:
  1. var uniqueCounter=0;
  2. function generateUniqueID()
  3.     {
  4.     uniqueCounter++;
  5.     return uniqueCounter.toString(16);
  6.     }

I wanted to have the number returned as hex which is why the .toString(16) is on the end. No real reason, it just seemed like the right thing to do. If you just want a number you can use this.

JavaScript:
  1. var uniqueCounter=0;
  2. function generateUniqueID()
  3.     {
  4.     return uniqueCounter++;
  5.     }

Question, Comments...

Do you have more questions. Please either leave a comment below or join us in our new forum.

2 Responses to “Generating element IDs with JavaScript and counters”

  1. Maybe it’s the way to do the same thing you posted before but without bug.. ?

    var uniqueCounter=0;
    function uid(){
    uniqueCounter++;
    var newDate = new Date;
    return newDate.getTime() + uniqueCounter++;
    }

  2. I didn’t really need it to be unique overall, just unique to the page. So a global counter worked for me. I did actually play with the Date object originally but found it was a little unnecessary for my needs.

    Like the idea though. Your code is simpler than what I came up with originally.

Leave a Reply