Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 978
Omar Abid Avatar asked Jul 21 '10 11:07

Omar Abid


People also ask

How do you uniquely identify a element in HTML?

Definition and UsageThe id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document). The id attribute is most used to point to a style in a style sheet, and by JavaScript (via the HTML DOM) to manipulate the element with the specific id.

What is a unique identifier for an element?

A unique identifier (UID) is an identifier that is guaranteed to be unique among all identifiers used for those objects and for a specific purpose. The concept was formalized early in the development of Computer science and Information systems. In general, it was associated with an atomic data type.

Can we provide a unique name to an element in HTML?

The name attribute is only valid on the <form> and form elements ( <input> , <textarea> and <select> ).

What is the main identifier of an element?

There are two properties that can be used to identify an element: the atomic number or the number of protons in an atom.


1 Answers

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;   }; }()); 
like image 91
RoToRa Avatar answered Sep 24 '22 02:09

RoToRa