Rotan075 Rotan075 - 7 months ago 14
Javascript Question

Toggle only the content within given div

I got a question regarding using the toggle function after a button press. I have the following jQuery code:

$(function () {
$('.navigation').click(function () {
$(".expand, .collapse").toggle();
});
});


This works perfect together with the following HTML:

<div class="container">
<div class="title">
<div class="navigation">
<span class="expand">
expand
</span>
<span class="collapse">
collapse
</span>
</div>
</div>
</div>


But whenever I have this HTML format:

<div class="container">
<div class="title">
<div class="navigation">
<span class="expand">
expand
</span>
<span class="collapse">
collapse
</span>
</div>
</div>
</div>

<div class="container">
<div class="title">
<div class="navigation">
<span class="expand">
expand
</span>
<span class="collapse">
collapse
</span>
</div>
</div>
</div>


The toggle is applied to both containers, which is logical but not desired. How could I trigger only the siblings of the pressed navigation button?

I tried something like:

$(this).next(".expand, .collapse").toggle();


but that does not work. Any help is appreciated!

DEMO HERE

Answer

You've got the right idea; you need to use the this keyword to reference the element which raised the event and find it's related .expand and .collapse elements, however next() looks for siblings, whereas the elements you need to retrieve are children so you need to use find():

$(function () {
    $('.navigation').click(function () {                                
        $(this).find(".expand, .collapse").toggle();
    });
});

Updated fiddle