JQuery $ (this) Choosing a child

I use this on the page:

jQuery('.class1 a').click( function() { if ($(".class2").is(":hidden")) { $(".class2").slideDown("slow"); } else { $(".class2").slideUp(); } }); 

With the structure on the page, it will later look like this:

 <div class="class1"> <a href="...">text</a> <div class="class2">text</div> </div> 

This works just fine unless you have multi-level classes class1 / class2:

 <div class="class1"> <a href="...">text</a> <div class="class2">text</div> </div> <div class="class1"> <a href="...">text</a> <div class="class2">text</div> </div> <div class="class1"> <a href="...">text</a> <div class="class2">text</div> </div> 

How to change jquery source code so that it only affects class2 under the current class1 that was clicked? I tried the options of what was recommended on this page: How to get children from the $ (this) selector? but havent got him to work yet

+59
jquery css-selectors children
May 08 '09 at 20:03
source share
4 answers

The best way with HTML that you have is probably to use the next function, for example:

 var div = $(this).next('.class2'); 

Since the click handler happens with <a> , you can also go to the parent DIV and then search down for the second DIV. You would do this with a combination of parent and children . This approach would be better if the HTML you are posting is not quite so, and the second DIV may be in another place relative to the link:

 var div = $(this).parent().children('.class2'); 

If you want the β€œsearch” not to be limited to immediate children, you should use find instead of children in the example above.

In addition, it is always better to add your class selectors with the tag name, if at all possible. those. if only the <div> tags will have these classes, make a div.class1 , div.class2 .

+82
May 08 '09 at 20:04
source share

It is much easier with . slideToggle () :

 jQuery('.class1 a').click( function() { $(this).next('.class2').slideToggle(); }); 

EDIT: made it .next instead of .siblings

http://www.mredesign.com/demos/jquery-effects-1/

You can also add cookies to remember where you are ...

http://c.hadcoleman.com/2008/09/jquery-slide-toggle-with-cookie/

+7
May 08 '09 at 20:17
source share

http://jqapi.com/ Moving β†’ Tree Walking β†’ Children

+5
May 08 '09 at 20:06
source share

There is a tag that was clicked in the click event "this"

 jQuery('.class1 a').click( function() { var divToSlide = $(this).parent().find(".class2"); if (divToSlide.is(":hidden")) { divToSlide.slideDown("slow"); } else { divToSlide.slideUp(); } }); 

There are several ways to get to the div, although you can also use .siblings, .next, etc.

+5
May 08 '09 at 20:10
source share



All Articles