Can't set element ID in JavaScript, it's always undefined

Posted by Dylaan Alith on Stack Overflow See other posts from Stack Overflow or by Dylaan Alith
Published on 2011-02-23T15:15:47Z Indexed on 2011/02/23 15:24 UTC
Read the original article Hit count: 220

Filed under:
|

Hi,

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');
},

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery