prototype: Add Element#identify, which returns the element's ID if it exists, or sets and returns a unique, auto-generated ID (of the form 'anonymous_element_' + auto-incremented digit) otherwise. Use this when you need to ensure an element has an ID. Closes #9012.

This commit is contained in:
Sam Stephenson 2007-07-24 17:41:27 +00:00
parent 7e6481bcd7
commit c6f3daadaa
3 changed files with 28 additions and 1 deletions

View File

@ -1,5 +1,7 @@
*SVN*
* Add Element#identify, which returns the element's ID if it exists, or sets and returns a unique, auto-generated ID (of the form "anonymous_element_" + auto-incremented digit) otherwise. Use this when you need to ensure an element has an ID. Closes #9012. [Jeff Watkins, sam, Tobie Langel]
* Make Element#readAttribute work for cloned elements in IE. Closes #8481. [chem, Tobie Langel]
* Template enhancements. Closes #8166. [Christophe Porteneuve]

View File

@ -233,6 +233,15 @@ Element.Methods = {
return Selector.findChildElements(element.parentNode, args).without(element);
},
identify: function(element) {
element = $(element);
var id = element.readAttribute('id'), self = arguments.callee;
if (id) return id;
do { id = 'anonymous_element_' + self.counter++ } while ($(id));
element.writeAttribute('id', id);
return id;
},
readAttribute: function(element, name) {
element = $(element);
if (Prototype.Browser.IE) {
@ -597,7 +606,7 @@ Element.Methods = {
}
};
Element.Methods.getElementsBySelector = Element.Methods.select;
Element.Methods.identify.counter = 1;
if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
function isArray(className) {
@ -636,6 +645,7 @@ if (!document.getElementsByClassName) document.getElementsByClassName = function
}(Element.Methods);
Object.extend(Element.Methods, {
getElementsBySelector: Element.Methods.select,
childElements: Element.Methods.immediateDescendants
});

View File

@ -342,6 +342,13 @@
<div id="inlineAbsoluted" style="position: absolute"></div>
<div id="unextended"></div>
<div id="identification">
<div id="predefined_id"></div>
<div></div>
<div></div>
<div></div>
<div id="anonymous_element_3"></div>
</div>
<!-- Tests follow -->
<script type="text/javascript" language="javascript" charset="utf-8">
@ -676,6 +683,14 @@
assert(element != $('intended'));
});
}},
testElementIdentify: function() {with(this) {
var parent = $('identification');
assertEqual(parent.down().identify(), 'predefined_id');
assertEqual(parent.down(1).identify(), 'anonymous_element_1');
assertEqual(parent.down(2).identify(), 'anonymous_element_2');
assertEqual(parent.down(3).identify(), 'anonymous_element_4');
}},
testElementClassNameMethod: function() {with(this) {
var testClassNames = $('container').getElementsByClassName('test');