Question

I recently asked just about the same question, but this one got a little twist to it so the answer from my previous question wont work and I'm not getting any answer on my comment.

As the title says, I want to select the nearest divtoexpand class when clicking button1.

<div class="test">
    <div class="menu">
        <div class="button1"></div>
    </div>
</div>
<div id="THETWIST"></div>
<div class="divtoexpand"></div>

<div class="test">
    <div class="menu">
        <div class="button1"></div>
    </div>
</div>
<div id="THETWIST"></div>
<div class="divtoexpand"></div>

Old code:

$('.button1').on('click', function() {
  $(this).closest('div.test').next('div.divtoexpand').slideDown();
});

This won't work when there is a div in between the test div and the divtoexpand..

Any suggestions?

Was it helpful?

Solution

Assuming you want the .divtoexpand that follows the ancestor of the .button1, then you're almost there:

$('.button1').on('click', function() {
    $(this).closest('.test').nextAll('.divtoexpand').first().slideDown();
});

OTHER TIPS

Try:

$(this).parent().parent().next().next('.divtoexpand').slideDown();

SEE DEMO

Change

$(this).closest('div.test').next('div.divtoexpand').slideDown();

to

$(this).closest('div.test').nextAll('div.divtoexpand').slideDown();

Refer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top