Chris Hansen
Chris Hansen

Reputation: 8647

closests jquery

<div class="panels">
    <div>
        <h2>
        Test
        </h2>
    </div>
    <div class="inner_panel statict">
         Test2
    </div>
</div>

I want so that when people click on Test, Test2 appears. If not, they don't see Test2, How can I make that happen using jquery?

I tried the following but it does not work.

 $('.inner_panel').hide();

  $('.panels').click(function () {
    $(this).closest('div .inner_panel').toggle();
  });

I have multiple divs with class panels in the file, so I don't want click on Test affecting the other "panels."

Upvotes: 1

Views: 122

Answers (3)

HeM01
HeM01

Reputation: 111

closest method looks up in the DOM tree, not down. You can check it here. http://api.jquery.com/closest/

Maybe you should use .children('div.inner_panel') to get your element. children method allows you to get elements, that are a single level down the DOM. Check http://api.jquery.com/children/ fo details.

Upvotes: 1

BJ Safdie
BJ Safdie

Reputation: 3419

 $('.inner_panel').hide();

 // Within .panels get the div's which contain an H2
 var containers = $('.panels h2').closest("div");

 // make them clickable
 containers.click(function () {
    // For the clicked panel, get the next element div which 
    // has the inner_panel class
    $(this).next('div.inner_panel').toggle();
 });

Upvotes: 0

Moin Zaman
Moin Zaman

Reputation: 25445

You have an extra space -> $(this).closest('div .inner_panel').toggle();

This should be: $(this).closest('div.inner_panel').toggle();

But .closest() is not going to work for you because it travels up the DOM tree and not up and then down to siblings etc.

I would do this:

$('.inner_panel').hide();

$('.panels').click(function () {
  $(this).find('div.inner_panel').toggle();
});

See jsbin demo

Upvotes: 0

Related Questions