With the following setup:
<div id="foo"/>
JavaScript (jQuery 1.8.0):
$('#foo').removeProp('id').prop('id', 'bar');
alert($('#bar').length);
alert($('#foo').length);
alert($('#undefined').length);
Note that the elements ID has not been updated to bar as I expected it to be (only the final alert yields 1) (Chrome 21)
This seems to be related to my use of removeProp('id'); which, whilst redundant in this example (when I can just set the id to bar directly), is required in my final code.
Now I’m curious as to what the correct way is to remove an ID in JavaScript; should I have used removeAttr()? Is this a bug in jQuery? Is it legal to remove an ID once setting it?
There are two things to note, here, the first is that the
idis an attribute, not a property, soattr()/removeAttr()should be used instead.The second is the the API for
removeProp()explicitly note that you should not:Also, rather than unsetting, and then setting, why not simply change it with
attr():