jQuery generate unique IDs

For generating random ids you could use this one.

<script type="text/javascript">
function Generator() {};

Generator.prototype.rand =  Math.floor(Math.random() * 26) + Date.now();

Generator.prototype.getId = function() {
   return this.rand++;
};
var idGen =new Generator();
</script>
</html>
<body>
<!-- Place this in the body of the page content -->

   <button onclick="console.log(idGen.getId())">click</button>

</body>

I didn't need a forever unique/random id, just something that was unique per page, and all of these solutions seemed overkill for me so I came up with this:

const uniqId = (() => {
    let i = 0;
    return () => {
        return i++;
    }
})();

// usage:
uniqId(); // 0
uniqId(); // 1
uniqId(); // 2
// ...

Since v1.9, jQueryUI has a builtin method for creating unique id's, called uniqueId().

This code will set a unique id on each element belonging to myclass.

$(".myclass").each(function () {
    $(this).uniqueId();
});

Note that, in my testing at least, you cannot assign a new id, if the element already has one.

So this div would get a unique id with the above Javascript code

<div class="myclass"/>

But this wouldn't

<div class="myclass" id="myId"/>

See https://api.jqueryui.com/uniqueId/ for more information