javascript - jQuery Selector for Section that Contains Divs -


i'd display of fields within section when h2 element within section clicked. example: when user clicks 'contact information' 3 form inputs (fields) below contact information heading shown.

all of form fields hidden following css:

div.field {   display:none; } 

here's jquery i'm using that:

$('section > h2').click(function(){   $('.field').toggle(); }); 

here's html:

<section>   <h2>contact information</h2>   <div class="field>     // form input   </div>   <div class="field>     // form input   </div>   <div class="field>     // form input   </div> </section>  <section>   <h2>address</h2>   <div class="field>     // form input   </div>   <div class="field>     // form input   </div>   <div class="field>     // form input   </div> </section> 

what happens here of fields shown - not ones within same section h2 being clicked. how can toggle visibility of fields within same section h2 being clicked?

thanks in advance.

go section, find .field elements within specific section

$('section > h2').on('click', function(){    $(this).closest('section').find('.field').toggle();  });
div.field {    display:none;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <section>    <h2>contact information</h2>    <div class="field">      form input 1    </div>    <div class="field">      form input 2    </div>    <div class="field">      form input 3    </div>  </section>    <section>    <h2>address</h2>    <div class="field">      form input 4    </div>    <div class="field">      form input 5    </div>    <div class="field">      form input 6    </div>  </section>

as long keep html is, siblings work well

$(this).siblings('.field').toggle() 

but it's more specific, , won't work nested elements


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -