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

javascript, jquery

Solution

 $('.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');

Problem

I want to hide any visible span elements if any is visible, and toggle it again if a element is clicked ``` <div class="item"> <a href="">element1</a> <span>span1</span> <br> </div> <div class="item"> <a href="">element2</a> <span>span2</span> <br> </div> <div class="item"> <a href="">element3</a> <span>span3</span> <br> </div> <div class="item"> <a href="">element4</a> <span>span4</span> <br> </div> ``` JS ``` $('.item span').hide(); var all_spans = $('.item a').parent().find('span'); $('.item a').click(function(e) { e.preventDefault(); // hide all span all_spans.hide(); $this = $(this).parent().find('span'); // here is what I want to do if ($this.is(':hidden')) { $(this).parent().find('span').show(); } else { $(this).parent().find('span').hide(); } }); ``` live example http://jsfiddle.net/BGSyS/ the issue is when I click for example '`element 1`' '`span1`' is still visible and I want to toggle this

Original source