0

I need to change the id attribute of a div on click.

<div class="xtra" id="id1"><a href="#"><span>Next</span></a></div> 

How would I do that?

I've tried:

$j("#id1").attr('id', 'id2');

but that didn't work.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Asim Zaidi
  • 27,016
  • 49
  • 132
  • 221

1 Answers1

4

try this:

$j("#id1").live('click',function(){
      $(this).attr('id', 'id2'); //use this one
      this.id = 'id2'; //or this one <-- they both do the same thing
})

I am not sure why you would ever want to do this, that is how you would do it.

IDs are not meant to change, they are meant to be unique to a specific element.

Classes are usually used when changing css back and forth.

Naftali
  • 144,921
  • 39
  • 244
  • 303
  • +1 for mentioning that IDs are not meant to change. Note that a sneaky consequence of using `live()` here is that the handler will no longer be triggered after the ID is changed. – David Tang Apr 11 '11 at 23:18
  • @Box9, the reason why i placed `live()` there was just in case the OP changes another element to that id – Naftali Apr 11 '11 at 23:20
  • @Neal Just `this.id = 'id2';` – Šime Vidas Apr 11 '11 at 23:24
  • @Neal, yup it makes perfect sense. I wasn't suggesting anything else - it's just something to be wary of since `live` doesn't attach the handler to the element itself. – David Tang Apr 11 '11 at 23:24
  • @Sime yes that too, ill add it to the answer – Naftali Apr 11 '11 at 23:24
  • @Neal My point is that setting the `id` property directly is better. In general, the `attr()` method is not needed for setting/getting DOM properties (properties on DOM elements defined by the DOM standards). There are a couple of exceptions like `href` and `src`. Read here: http://stackoverflow.com/questions/4456231/retrieving-html-attribute-values-the-dom-0-way – Šime Vidas Apr 11 '11 at 23:50