- MooTools 1.3 Cookbook
- Jay Larry G. Johnston
- 318字
- 2021-04-02 19:07:09
Adding an element with a unique ID
We will inject new blood into our message by adding a new HTML element to the page.
Getting ready
The Element
class deals with methods such as inject()
and destroy()
. There are also classes for String
and Number
among others. When faced with a need to add an element with a unique ID attribute, we turn to String.uniqueID().
This method uses Date.now()
to return a string that will be, invariably, unique.
How to do it...
Note that to make a copy of our existing my_target
we use Element.clone()
.
<script type="text/javascript" src="mootools-1.3.0.js"></script> </head> <body> <form action="javascript:" method="get"> <input type="button" value="Unique Me!"/> </form> <div id="my_target" style="width:150px; height:150px; border:1px solid #BEBEBE; line-height:50px; text-align:center; float:left;"></div> <noscript>JavaScript is disabled.</noscript> <script type="text/javascript"> $$('input[type=button]').addEvent('click',function() { var element_to_copy = $('my_target'); // A var my_target_id = element_to_copy.get('id'); // B var my_unique_id = String.uniqueID(); // C var my_cloned_target = element_to_copy.clone(); // D my_cloned_target.set('id',my_unique_id); // E my_cloned_target.set('text',my_unique_id); // F my_cloned_target.inject(element_to_copy,'after'); }); </script> </body> </html>
How it works...
In line C, we use the String
class to initialize a unique value in my_unique_id
. There are many methods such as uniqueID()
that are available to this class like test(), trim(), capitalize()
, and toInt()
to name a few.
There's more...
There are several shortcuts that we could take in this recipe.
- Combine A and B in our example like this:
my_target_id = $('my_target').get('id');
- If we combine A and B, update D:
var my_cloned_target = $('my_target').clone();
- The method
set()
can take an object of properties to merge E and F:my_cloned_target.set({'id':my_unique_id, 'text':my_unique_id});
- Finally, we could chain the actions for
my_cloned_target:
my_cloned_target.set({'id':my_unique_id, 'text':my_unique_id}).inject($('my_target'),'after');
- In fact, the only line that cannot be collapsed is the initialization of the unique ID:
$$('input[type=button]').addEvent('click',function() { var my_unique_id = String.uniqueID(); //C $('my_target').clone().set({'id':my_unique_id, 'text':my_unique_id}).inject($('my_target'),'after'); });
Cloning an object does remove the ID attribute, though that does not help us if we need unique IDs for any reason. The ID attribute must always be unique in the DOM. We may note that Firefox internally tracks each ID uniquely; however, Internet Explorer and others will not be so forgiving. Keep ID attributes unique!