Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery remove class from many, add class to one

A common operation I find myself doing is the following:

<ul>
    <li>One</li>
    <li class="current">Two</li>
    <li>Three</li>
</ul>

var $allLi = $('li');

$allLi.click(function(){
    $allLi.removeClass('current');
    $(this).addClass('current');
});

Is there a way to condense this, somehow by combining $allLi and $(this) and using toggleClass?

Thanks!

like image 211
HandiworkNYC.com Avatar asked Apr 27 '12 18:04

HandiworkNYC.com


2 Answers

Jonathan's solution should work just fine but I would like to propose a different solution.

Rather than unsetting all the elements and then selecting the current one, why not just keep track of the current element and only perform the operation on that?

<ul>
    <li>One</li>
    <li class="current">Two</li>
    <li>Three</li>
</ul>

<script type="text/javascript">
    (function () {
        var current = $("li.current");
        $("li").click(function () {
            current.removeClass("current");
            current = $(this);
            current.addClass("current");
        });
    }());
</script>

It's "longer" but also more efficient.

My solution aims to have all state in JavaScript rather than partly in the DOM. toggleClass circumvents this principle. It's not so much a matter of "hey looks this a really long and super complex way of doing something simple", there's an idea behind it. If your application state gets more complex than just one selected element you'll run into issues if you try and stuff that state into the DOM. The DOM is just a 'view', keep your state in the 'model' (the JS code).

like image 118
Halcyon Avatar answered Sep 24 '22 14:09

Halcyon


I believe you could add it, and remove it from the siblings:

$("li").on("click", function(){
  $(this)
    .addClass("current")
    .siblings()
      .removeClass("current");
});

Demo: http://jsbin.com/owivih/edit#javascript,html,live

like image 40
Sampson Avatar answered Sep 22 '22 14:09

Sampson