klye_g
klye_g

Reputation: 1242

this find parent of another div and toggle its child using jQuery

I've done some research and nothing seems to be working. Here is the HTML followed by the JavaScript I am putting together. What I am trying to do is set it up so that whenever dashboard_gear_options is clicked, it toggles the appropriate hidden options row. Each block of code exists multiple times at different locations on the page. I tried using this, find, parent, next and children to no avail.

HTML:

// start block
<div class="content_block_holder">
   <div class="content_top">
      <div class="dashboard_gear_options"></div>
      <div class="dashboard_gear_divider"></div>
   </div>
   <div class="dashboard_holder">
      <div class="hidden_options_row"></div>
   </div>
</div>
// end block

// start block
<div class="content_block_holder">
   <div class="content_top">
      <div class="dashboard_gear_options"></div>
      <div class="dashboard_gear_divider"></div>
   </div>
   <div class="dashboard_holder">
      <div class="hidden_options_row"></div>
   </div>
</div>
// end block (etc..)

JS:

$(document).ready(function(){
   $('.dashboard_gear_options').click(function(){
       $(this).parent('.content_block_holder').find('.hidden_options_row').toggle();        
    });
});

Upvotes: 2

Views: 2775

Answers (3)

Charlie Rudenst&#229;l
Charlie Rudenst&#229;l

Reputation: 4338

Try using closest([selector]) ( http://api.jquery.com/closest/ ) instead of parent in your selector. It will traverse up the tree and find "content_block_holder". parent([selector]) will just check the immediate parent and return an empty set if it doesn't match the selector provided.

$(document).ready(function(){
   $('.dashboard_gear_options').click(function(){
       $(this).closest('.content_block_holder').find('.hidden_options_row').toggle();        
   });
});

JSFiddle based on your code: http://jsfiddle.net/gK7yM/

Upvotes: 3

Stano
Stano

Reputation: 8949

Also this chain works:

$(this).parent().next('.dashboard_holder').children('.hidden_options_row').toggle();

or

$(this).parent().next('.dashboard_holder').find('.hidden_options_row').toggle();

Upvotes: 0

mgraph
mgraph

Reputation: 15338

try this

$(this).closest('.content_block_holder').find('.dashboard_holder').find('.hidden_options_row').toggle();        

Upvotes: 2

Related Questions