Question

Looks like simple but I cant find why it is not working. I am only trying to "removeClass" of the siblings of the rest siblings "a" tags when I click one of them. What I am doing wrong? Thanks in advance.

CSS ------->

.navigation li a{
    display: block;
    padding: 10px;
    text-decoration: none;
    color: #544539;
    font-size: 18px;
    background: #FFFFFF;
}

a.selected {
    background: #003662;
    color: #ffffff;
}

HTML------->

<nav class="navigation">
    <ul>
        <li><a href="#" title="home">Home</a></li>
        <li><a href="#" title="collect">Collect</a></li>
        <li><a href="#" title="spend">Spend</a></li>
        <li><a href="#" title="about">About Us</a></li>
    </ul>
</nav>

jQuery ------->

$(".navigation a").on("click", function() {                              
    $(this).addClass("selected");
    $(this).siblings().removeClass("selected");
});
Was it helpful?

Solution 3

use:

$(this).parent().siblings().find('a').removeClass("selected");//remove class from sibling a tags
$(this).addClass("selected");//and then add class to current a tag

you can also use:

 $('.selected').removeClass("selected");
 $(this).addClass("selected");

OTHER TIPS

You just need to remove class active from all anchors and add it to current clicked anchor:

$(".navigation a").on("click", function() {                              
    $('.navigation a').removeClass("selected");
    $(this).addClass("selected");
});

Fiddle Demo

do this in your JS

$(".navigation a").on("click", function() {                              
    $(this).addClass("selected");
    $(this).siblings().removeClass("selected");
 });

http://jsfiddle.net/mahavir4dev/v9LGY/

Try simple way:

http://jsfiddle.net/aamir/fWKsV/

Change css to:

li.selected a {
    background: #003662;
    color: #ffffff;
}

jQuery:

$(".navigation a").on("click", function() {                              
    var $li = $(this).closest('li');
    $li.addClass('selected')
    $li.siblings().removeClass("selected");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top