Unique identifier for HTML elements

Besides the ID, if you say you want a unique identifier for an HTML element (let’s say a div).

I browsed the DOM for something (like a number or string) that was unique for each element; but the DOM was big and I failed to find that on the Internet.

Is there a property (in the DOM obviously) that is unique only to that element? (Other than the ID and also you don't specify it, but it comes when the DOM is constructed.)


Solution 1:

Depending on the objective, here are two suggestions.

Unless you actually need to express the id as some kind of string, you can save the normal DOM reference.

If you do need to express it as a string for some reason, then you'll need to assign a unique id yourself.

var getId = (function () {
  var incrementingId = 0;
  return function(element) {
    if (!element.id) {
      element.id = "id_" + incrementingId++;
      // Possibly add a check if this ID really is unique
    }
    return element.id;
  };
}());

Solution 2:

The only other identifier I can think of is the XPath of the element in the document.

For instance, the title link inside the heading of this very page has an XPath of

/html/body/div[3]/div[2]/div/h1/a

But like Pekka already said, it depends on what you want to do. And I don’t think you can get the XPath easily from the DOM in JavaScript, despite XPath being available nowadays in JavaScript engines.

Solution 3:

Internet Explorer has a property, "uniqueID", for every element. The problem is that the other browsers don't support it.

Solution 4:

You can use a library or roll your own to create a unique identifier. jQuery has .data():

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.