Dima Deplov
Dima Deplov

Reputation: 3718

jQuery work remove id but not an element

I have a bunch of spans, I can click on each of it and this element will be with id="active" for example. But how to remove id="active" from previous element?

$('#active').attr("id",'');  
$(this).attr("id","active");

I use this, is this valid? After this code, elements that was an active element but now isn't active has id but it's look like

<span class="bunch_of_spans" id> // not active anymore (but can be active if i pick it)
<span class="bunch_of_spans" id="active"> // active now
<span class="bunch_of_spans"> // never was active

Is this valid and may be there is method to remove id from elements that doesn't active? Thanks

Upvotes: 0

Views: 2610

Answers (2)

To answer your specific question, use:

$('#active').removeAttr("id");

But semantically, the id's should never change, so I recommend you to use classes instead, like:

<span class="bunch_of_spans active">

and you add/remove the class like this:

$('#active').addClass("active");
$('#active').removeClass("active");

Upvotes: 2

RAS
RAS

Reputation: 3385

use removeAttr

$('#active').removeAttr("id");  

Working example:
http://jsfiddle.net/nWtYc/

Although this will work I suggest you to use some other non-unique identifier to identify active elements. classes work good for this.

Upvotes: 4

Related Questions