Show/ Hide only sibling divs jquery

400 views Asked by At

I have multiple divs on my webpage with the same class name. When i click on span (+/-) each div with the same class name get show/ hide. I want to show/ hide only sibling divs on click to +/- button. I tried a lot to find solution but could not reach to my solution. Thanks...

HTML:

<div class="abc">
  <div class="abc1">
    Stallone Manor is a 200 ft x 130 ft covered AC hall enchanted with a classic touch of Roman grandeur & grace. We offer one of the largest banquet halls in the city.<span>(-)</span>
  </div>
  <div class="abc2">
    Stallone Manor is a 200 ft x 130 ft covered AC hall enchanted with a classic touch<span>(+)</span>
  </div>
</div>

<div class="abc">
  <div class="abc1">
    Stallone Manor is a 200 ft x 130 ft covered AC hall enchanted with a classic touch of Roman grandeur & grace. We offer one of the largest banquet halls in the city.<span>(-)</span>
  </div>
  <div class="abc2">
    Stallone Manor is a 200 ft x 130 ft covered AC hall enchanted with a classic touch<span>(+)</span>
  </div>
</div>

Jquery:

$(document).ready(function() {
    $(".abc2 span").click(function(){
        $(".abc2").hide();
        $(".abc1").show();
    });
    $(".abc1 span").click(function(){
        $(".abc1").hide();
        $(".abc2").show();
    });
});

Fiddle:

http://jsfiddle.net/berqK/42/

1

There are 1 answers

0
Rajaprabhu Aravindasamy On BEST ANSWER

You have to target the elements by using this,

$(document).ready(function() {
    $(".abc2 span").click(function(){
        var par = $(this).parent(".abc2").hide();
        par.prev(".abc1").show();
    });
    $(".abc1 span").click(function(){
        var par = $(this).parent(".abc1").hide();
        par.next(".abc2").show();
    });
});

DEMO

You could optimize the solution like below,

$(document).ready(function() {
    $(".abc1,.abc2").find("span").click(function(){
        var par = $(this).parent().hide(), isAbc1 = par.is(".abc1");
        par[isAbc1 ? "next" : "prev"](isAbc1 ? ".abc2" : ".abc1").show();
    });
});

DEMO