0

I am trying to addClass of blue to when the next current li is clicked and removeClass of the previous li. However, I can't seem to get it working, it adds the class to the other li instead, but seems to remove the previous class.

Fiddle: https://jsfiddle.net/5otouLxg/1/

var $li = $("li a#t1:first-child");
var $li2 = $("li a#t2:first-child");
$('li').click(function () {
    if ($li.children().has

var $li = $("li a#t1:first-child");
var $li2 = $("li a#t2:first-child");

$('li').click(function () {
    if ($li.children().hasClass('nav-1')) {
        $li.children().addClass('blue');
        $li2.children().removeClass('blue');
    }
    if ($li2.children().hasClass('nav-2')) {
        $li.children().removeClass('blue');
        $li2.children().addClass('blue');
    }
});
.blue {
    color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<li>
    <a id="t1">
        <span class="nav-1">HELLO</span>
    </a>
</li>
<li>
    <a id="t2">
        <span class="nav-2">HELLO</span>
    </a>
</li>

1

2 Answers 2

2

I think you can achieve what you want by simplifying your code: works with Two li's or A bunch of li's

$('li').click(function () {
    $(this).children('a').addClass('blue');
    $(this).siblings().children('a').removeClass('blue');
});
3
  • Should be $(this).find('span') to stay consistent with what the original accomplished, otherwise good answer.
    – Oceanity
    Commented Mar 12, 2015 at 3:26
  • Why does the span matter? OP just wanted to find the next li according to the description. Commented Mar 12, 2015 at 3:27
  • li colors the bullet and text, span only colors text
    – Oceanity
    Commented Mar 12, 2015 at 3:28
0

I've use another script to make it works

$('li').click(function(){
    $('li').removeClass('blue');
    $(this).addClass('blue');
});

The script will remove all 'blue' class of all the li (if more than 2), and add the class to the one that's been clicked.

Hope this is what you need.

Fiddle DEMO

Not the answer you're looking for? Browse other questions tagged or ask your own question.