jQuery child & gt; parent & gt; child

advertisements

I have this html-code:

<div class="im">
<div style="height:220px">HELLO WORLD!
<a class="close">X</a>
<a class="open" style="display:none;">V</a>
</div>
</div>

<div class="im">
<div style="height:220px">HELLO WORLD!
<a class="close">X</a>
<a class="open" style="display:none;">V</a>
</div>
</div>

and I want to press X (class close) to change height of parent div to 20px and show V (class open), but hide X (class close) in each div with class im separately. Then press V (class open) to change height of parent div to 220px and show X, but hide V.

So I wrote this code to do it, but when I press X, it show BOTH V (class open), but I want to show only one of them, which is in the parent's div:

$('.close').click(function(){ // click X makes
  $(this).parent().css('height','20px'); // parent div's height = 20px
  $(this).hide('fast'); //hide X
  $('.open').show('fast');} //unhide V
);
$('.open').click(function() {
  $(this).parent().css('height','220px');} // change height of parent div to 220px
  $(this).hide('fast'); //hide V
  $('.close').show('fast');} //unhide X
);

How can I hide and show only one of V, which is child of the parent div, which is parent of X (class .close).


Since X and V are siblings, you can use the aptly-named siblings() method:

$(".close").click(function() {
    $(this).parent().css("height", "20px")
           .end().hide("fast")
           .siblings(".open").show("fast");
});

$(".open").click(function() {
    $(this).parent().css("height", "220px")
           .end().hide("fast")
           .siblings(".close").show("fast");
});