Reputation: 4001
I have a List item where if I click on any of the list item it adds an ID "current" .
But If I click again on this list this "current" ID should removed and back to normal again, something like toggling. I am able to add the attribute but not the able to toggle. Any help will be appreciated.
JS
$('ul li').click(function(){
$('ul li').removeAttr("id","current");
$(this).attr("id","current");
});
Upvotes: 0
Views: 815
Reputation: 24638
Here is how to toggle:
$('ul li').click(function(){
$('ul li').not(this).removeAttr("id");
if( $(this).attr('id') == 'current' )
{
$(this).removeAttr('id');
}
else
{
$(this).attr("id","current");
}
});
Use of a css class would be most recommended for work like this:
$('ul li').click(function(){
$('ul li').not(this).removeClass("current");
$(this).toggleClass('current');
});
Upvotes: 1
Reputation: 1821
Try this:
$('ul li').click(function(){
if($(this).attr("id") == "current"){
$(this).removeAttr("id");
}else{
$(this).attr("id","current");
}
});
Upvotes: 0
Reputation: 207901
It should be $('ul li').removeAttr("id");
.
On a related note, it's best to use classes instead of IDs for stuff like this.
Update:
To toggle, use classes like:
$('ul li').click(function () {
$('ul li').not(this).removeClass("current");
$(this).toggleClass("current");
});
Upvotes: 4