jAC jAC - 2 months ago 19
CSS Question

jquery toggle one div with same class when div is not in the same code block

I have a very simple problem but I cannot find a solution to this. I have found many references to using .parent(), .next(), .find() but none of them are doing what I expect. Ether all the divs with the same class name are expanding and collapsing at the same time or they do not work at all.

So what I am looking for here is to have the same class names and expand and collapse only the one I click. I have something that is like this:

HTML:

<table>
<tr>
<td><div class="expand">More Details</div></td>
<tr/>
<tr>
<td>
<div class="extras" style="display:none;">
<table>
<tr><td>Some Data</td></tr>
</table>
</div>
</td>
</tr>
<tr>
<td><div class="expand">More Details</div></td>
<tr/>
<tr>
<td>
<div class="extras" style="display:none;">
<table>
<tr><td>Some Data</td></tr>
</table>
</div>
</td>
</tr>
</table>


jQuery:

$(".expand").click(function() {
$(".extras").toggle();
});


This will expand and collapse all of them when I only want it to do so on the one that is clicked in the "expand" div to trigger the below "extras" div.

Any thoughts would be appreciated.

Answer
$(".expand").click(function() {
    $(this).closest("tr").next("tr").find(".extras").toggle();
});

Means:

$(this)           // Start from here
.closest("tr")    // go up
.next("tr")       // go to next
.find(".extras")  // find element
.toggle();        // do tha thing
Comments