Jquery remove class from many, add class to one
Asked Answered
G

2

5

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!

Gibeonite answered 27/4, 2012 at 18:59 Comment(1)
What you are doing is about as efficient as it can be using jQuery methods.Milagrosmilam
D
5

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).

Detribalize answered 27/4, 2012 at 19:8 Comment(4)
Why wouldn't you simply add the class in the same line of the setter?Aleras
Please don't make trivial edits to my code. Yes I know current = $(this).addClass("current"); works, but does it make the code more readable? no.Detribalize
Then I suppose we'll just have to disagree on that :) but as it's my solution I'd like to keep it to my preference.Detribalize
Ok by me ... just thought I was helping you out.Aleras
T
4

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

Teevens answered 27/4, 2012 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.