views:

24258

answers:

5

I need to change an element ID.
(yep, jQuery newbie)

Apparently these don't work:

jQuery(this).prev("li").attr("id")="newid"
jQuery(this).prev("li")="newid"

I found out that I can make it with the following code

jQuery(this).prev("li")show(function() {
    this.id="newid";
});

But that doesn't seem right to me. There must be a better way, no? Also, in case there isn't what other method can I use instead of show/hide or other effects? Obviously I don't want to show/hide or affect the element every time, just to change its id.

(again, jQuery newbie)

Thanks

edit I can't use classes in this case, must be ids

+2  A: 

I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.

Tim K.
I have to use id's as a way to hack into an existing system. no way around it...
yoavf
the joys of legacy systems - I understand your pain then. Eran answer is definitely the best then.
Tim K.
+25  A: 

Your syntax is incorrect, you should pass the value as the second parameter:

jQuery(this).prev("li").attr("id",newId);
Eran Galperin
I think newId should be in quotes
CarolinaJay65
Don't you need to detach the element from the DOM and replace it with a new element with a new ID in it's place? To avoid breaking the DOM ...?
roosteronacid
jQuery takes care of that, roosteronacid.
McPherrinM
+10  A: 

What you mean to do is:

jQuery(this).prev("li").attr("id", "newID");

That will set the ID to the new ID

Pim Jager
+1  A: 

I did something similar with this construct

$('li').each(function () { if (this.id) this.id = this.id+"something" });

+1  A: 

I can imagine that cloning an object with an id can cause problems. So changing the id when cloning makes sense.

Cor