How can I toggle the element that is clicked and hide all others?

 $('.item span').hide();

$('.item a').click(function(e){

    e.preventDefault();
    // hide all span
    var $this = $(this).parent().find('span');
    $(".item span").not($this).hide();

    // here is what I want to do
    $this.toggle();

});

Check demo

Update with explanation:

The problem is when you hide all spans, you also hide the current span => all spans have the same state (hidden), and your next line display it again. You have to exclude the current element when hiding and use toggle method to toggle its state (simpler than using if to check)

Another problem is try to avoid implicit global by using var to declare $this:

var $this = $(this).parent().find('span');

Leave a Comment