On clicking a span, remove all classes from the other spans under the same parent
There have been a few questions that are similar but are either too broad or don't show good example code.
All I want to do is if a user clicks on span bButton
, then the selected
class is removed from all of the other spans and replaced with the notSelected
class.
<div id="mainNav">
<span id="aButton" class="button selected">a</span>
<span id="bButton" class="button notSelected"&g开发者_高级运维t;b</span>
<span id="cButton" class="button notSelected">c</span>
</div>
What is the jQuery solution to this?
Thanks!
- Remove the
notSelected
class from the clicked element. - Add the
selected
class to the clicked element. - Remove the
selected
class from all siblings. - Add the
notSelected
class to all siblings.
$('#mainNav > span').click(function() {
$(this)
.removeClass('notSelected')
.addClass('selected')
.siblings()
.removeClass('selected')
.addClass('notSelected');
});
jsFiddle.
As a sidenote, I wouldn't bother with the notSelected
class.
You could decide on which element is selected by the presence of selected
or not. If the element does not have the selected
class, then it is not selected.
Try this:
$('span').click(function(){
$(this).parent().children('span').each(function(){
$(this).removeClass('selected').addClass('notSelected');
});
$(this).removeClass('notSelected').addClass('selected');
});
Working example: http://jsfiddle.net/AlienWebguy/SnnzV/
$('span').live('click',function(){
$(this).removeClass('notSelected');
$(this).addClass('selected');
$(this).siblings().each(function(){
$(this).removeClass('Selected');
$(this).addClass('notSelected');
});
});
精彩评论