Jquery $(this) Child Selector
Solution 1:
The best way with the HTML you have would probably be to use the next
function, like so:
var div = $(this).next('.class2');
Since the click handler is happening to the <a>
, you could also traverse up to the parent DIV, then search down for the second DIV. You would do this with a combination of parent
and children
. This approach would be best if the HTML you put up is not exactly like that and the second DIV could be in another location relative to the link:
var div = $(this).parent().children('.class2');
If you wanted the "search" to not be limited to immediate children, you would use find
instead of children
in the example above.
Also, it is always best to prepend your class selectors with the tag name if at all possible. ie, if only <div>
tags are going to have those classes, make the selector be div.class1
, div.class2
.
Solution 2:
In the click event "this" is the a tag that was clicked
jQuery('.class1 a').click( function() {
var divToSlide = $(this).parent().find(".class2");
if (divToSlide.is(":hidden")) {
divToSlide.slideDown("slow");
} else {
divToSlide.slideUp();
}
});
There's multiple ways to get to the div though you could also use .siblings, .next etc