get or set an element's unique id with MooTools
Sunday, October 05, 2008
Here is a simple MooTools script that adds a getId method to the Element class. The getId method simply returns the element's id if it already exists, if not it generates a unique id, assigns it to the element and returns that. The generated id does not persist from page to page, however this little script comes in handy sometimes.
Element.implement({
getId: function(){
if(!this.get('id')){
var uniqueId = this.get('tag') + "-" + $time();
while($(uniqueId)){ uniqueId = this.get('tag') + "-" + $time(); }
this.set('id', uniqueId);
}
return this.get('id');
}
});
So usage would look like this:
var theIdofTheFirstLink = $(document.body).getElement('a').getId();
//or something like this would make sure every element on the page has an id
$$('*').getId();
Labels: javascript, mootools
0 Comments:
Post a Comment
<< Home