Prototype.js has a method, Element.identify(), that can be very useful. It is used to retrieve the ID of a given element. If one does not exist it first generates and assigns one and then returns that.
To implement this in MooTools you can add the following code.
Element.implement({
identify: function() {
if(!$type(this.get('id')))
this.set('id', genID(0));
return this.get('id');
function genID(num) {
num++;
if(!$type($(num.toString())))
return num;
return genID(num);
}
}
});So, if you have the following elements
<span class='xyz'>Lorem</span>
<span class='xyz'>Ipsum</span>
<div id='2'>Dolor</div>and you execute the following in MooTools which applies identify() on each span
window.addEvent('domready', function() {
$$('span.xyz').each(function(span) {
span.identify();
});
});then you will end up with the following HTML.
<span class='xyz' id='1'>Lorem</span>
<span class='xyz' id='3'>Ipsum</span>
<div id='2'>Dolor</div>As simple as this is, it becomes very useful when dealing with dynamic content. You can now use the $ function to select distinct elements. But, beware that in CSS trying something like
#1 {
color:red;
}won't work in most browsers. When applying style to an element the element's ID should start with a letter. But you can still use JavaScript to apply any attributes.