jQuery Javascript create unique ID for an Element

Hi Guys,

There are time when you want to create a unique ID on the Fly either from your JQuery plugin or your usual JavaScript Code

Here are couple of ways I use without extending the Object class

First method


You can use the above method to return uniq id as shown below

Second method

In second method we will use a counter as shown below

Above method use an object with has one property counter and a method get


Above can be utilized in your code as shown below

I have typed above code directly in this post rather than copy pasting

If you find any error in above method or want to suggest any other method please leave your comments.








  1. On line 11 of the second method, it should pass the prefix back into the get method otherwise it will use uniqid when jQuery finds a matching ID using the initially supplied prefix

  2. spamfilter@pcshome.net says

    In line 7 of the first method, it should be idlength otherwise it returns an empty string.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.