views:

131

answers:

5

HTML:

<ul class="parent">
   <li><a href="#">toggler</a>
       <ul class="child">
       ...
       </ul>
   </li>
</ul>

I'd like to toggle 'child' UL (if it exists) via 'toggler' link. There might me multiple parent>child elements so I'd like to toggle the relevant child only.

Thanks in advance for your help.

A: 
$('ul.parent li a').click(function(event) {

    $(this).next('ul.child').slideToggle(500);
    event.preventDefault();

});

Have you considered instead of using a link there, a <button>.

alex
A: 
$("a.toggler").click(function(){
   $(this).parent().children('.child').toggle();
});
Darmen
+1  A: 

Given your link has an id:

<a id="Mylink" href="#">

The jQuery would be:

$("#MyLink").click(function(){
    $(this).siblings('.child').toggle();
});

You could select directly by element and class instead of ID:

$('ul.parent li a')

But ID selectors are generally considered to be faster

The toggle function also accepts a parameter if you wish to animate, e.g.

    $(this).siblings('.child').toggle('slow');  /or 'medium', or 'fast'
    $(this).siblings('.child').toggle(100); //100 millisecs

A variation to this is slideToggle, with the same parameters.

    $(this).siblings('.child').slideToggle('slow');

http://docs.jquery.com/Effects/toggle

James Wiseman
.child is a sibling of the anchor, not a child.
David
Good spot. Some would have constitued that a down-vote. Have corrected accordigly. +1 for your answer
James Wiseman
+2  A: 

The UL is not a child to the anchor, but using next() is simple enough:

$('ul a').click(function() {
     $(this).next().toggle();
});
David
A: 
$('.parent a').click(function () {
  $('.child', this.parentNode).toggle();
});
Gleb M Borisov