Generating Unique Ids on the Fly

Let’s do some JavaScript!

This post may be a little off-topic from my normal content, although it isn’t Xamarin, it could be used for hybrid frameworks like Ionic or base Cordova.

What we’re going to do is look at ways to generate unique ids on the fly for anchor tags. This could be used to help with your Google analytics or general user interaction tracking.

First thing we need is a function to generate the ids:


var lastId = 0;
function uniqueId(prefix){
    lastId++;
    return prefix+lastId;
}

Now what we need to do is use this function to set the ids on all our anchors:


document.addEventListener("DOMContentLoaded", function(event) {
    var anchors = document.getElementsByTagName("a")
    for(var i = 0; i < anchors.length; i++){
        anchors[i].id = uniqueId("generatedId");
    }
});

Doing it this way ensures that our ids are the same each time we load the page since it is based on their position when the DOM is loaded. This set up isn’t fool proof, obviously. If your page’s content is inconsistent, tags could end up with different ids than they had before. Some of these problems can be handled better by using a smarter prefix for your id.