Unable to set element ID in JavaScript, it is still undefined

advertisements

I want to have a function that generates ID's on the fly for a given jquery object, if it doesn't have one already. These ID's should then be used in future requests.

I came up with the code below, but it doesn't work. The ID's are never set. The commented out alert statement below always return undefined.

I always pass code like $(this) or $(options.el) as a parameter to substitute 'el'. Initially, the elements do not have explicitly ID set in HTML.

Any help would be appreciated, here's the code:

getElementId: function(el)
{
   if(undefined == el.attr('id'))
   {
      el.attr('id',"anim-"+Math.random().toString().substr(2));
   }
   // alert(el.attr('id'));
   return el.attr('id');
},


Try changing:

if(undefined == el.attr('id'))

to:

if("" == el.attr('id'))