Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

javascript - Unique identifier for HTML elements

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Pekka says, it would be easier if you would describe what you want to do. Until then 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;
  };
}());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...