IT戦記

プログラミング、起業などについて書いているプログラマーのブログです😚

要素固有の ID を取得する

IE では

element.uniqueID

というのがある。
これは、要素に固有の番号を付けたものだ。
これが結構便利で、

var seen = {};
for (var i = 0; i < elemenets.length; i ++) {
  if (seen[elements[i].uniqueID])
    elements.splice(i, 1);
  else
    seen[elements[i].uniqueID] = true;
}

みたいな感じで、使うことができる。

他のブラウザ

他のブラウザにはこれがないので、結構不便。
で、 getter で出来るじゃんって思ってググってみたら。
Dean Edwards さんがもう作ってた。さすが
http://dean.edwards.name/moz-behaviors/src/

HTMLElement.prototype.__defineGetter__("uniqueID", function() {
 // a global counter is stored privately as a property of this getter function.
 // initialise the counter
 if (!arguments.callee.count) arguments.callee.count = 0;
 // create the id and increment the counter
 var $uniqueID = "moz_id" + arguments.callee.count++;
 // creating a unique id, creates a global reference
 window[$uniqueID] = this;
 // we don't want to increment next time, so redefine the getter
 this.__defineGetter__("uniqueID", function(){return $uniqueID});
 return $uniqueID;
});

ちょっとだけ自分用にカスタマイズ

(function() {
    var nextUniqueID = 1; 
    HTMLElement.prototype.__defineGetter__('uniqueID', function() {
        var uniqueID = 'id' + nextUniqueID++
        this.__defineGetter__("uniqueID", function(){return uniqueID});
        return uniqueID;
    });  
})();

id:javascripter さんの指摘で直しました><ありがとうございます><

これ便利だなー

(Dean Edwards)++