Skip to content

Commit 40e47c0

Browse files
committed
Core: Add the uniqueId() and removeUniqueId() methods written by @scottgonzalez to provide a generalized way of generating and removing generated element id's. Also, added a unit test. Fixed #8361 - Add uniqueId() and removeUniqueId()
1 parent 649a670 commit 40e47c0

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

tests/unit/core/core.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,4 +153,14 @@ test( "outerHeight(true) - setter", function() {
153153
equal( el.height(), 32, "height set properly when hidden" );
154154
});
155155

156+
test( "uniqueId / removeUniqueId", function() {
157+
var el = $( "img" ).eq( 0 );
158+
159+
equal( el.attr( "id" ), undefined, "element has no initial id" );
160+
el.uniqueId();
161+
ok( /ui-id-\d+$/.test( el.attr( "id" ) ), "element has generated id" );
162+
el.removeUniqueId();
163+
equal( el.attr( "id" ), undefined, "unique id has been removed from element" );
164+
});
165+
156166
})( jQuery );

ui/jquery.ui.core.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
*/
1010
(function( $, undefined ) {
1111

12+
var uuid = 0,
13+
runiqueId = /^ui-id-\d+$/;
14+
1215
// prevent duplicate loading
1316
// this is only a problem because we proxy existing functions
1417
// and we don't want to double proxy them
@@ -107,6 +110,22 @@ $.fn.extend({
107110
return 0;
108111
},
109112

113+
uniqueId: function() {
114+
return this.each(function() {
115+
if ( !this.id ) {
116+
this.id = "ui-id-" + (++uuid);
117+
}
118+
});
119+
},
120+
121+
removeUniqueId: function() {
122+
return this.each(function() {
123+
if ( runiqueId.test( this.id ) ) {
124+
$( this ).removeAttr( "id" );
125+
}
126+
});
127+
},
128+
110129
disableSelection: function() {
111130
return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
112131
".ui-disableSelection", function( event ) {

0 commit comments

Comments
 (0)