<div class="wrap"> <div class="Level2">Click me</div> <div class="Level3">Information</div> </div> <div class="wrap"> <div class="Level2">Click me</div> <div class="Level3">Information</div> </div> <div class="wrap"> <div class="Level2">Click me</div> <div class="Level3">Information</div> </div> <div class="wrap"> <div class="Level2">Click me</div> <div class="Level3">Information</div> </div>
jQuery
$('.Level2').click(function(){ $('.Level2').closest('.Level3').fadeToggle(); });
I wanted to select the closest level3 to fadeIn and fadeOut, but doesn't work. Is my syntax wrong? online Sample :http://jsfiddle.net/meEUZ/
The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.
In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.
Definition and UsageThe closest() method searches up the DOM tree for elements which matches a specified CSS selector. The closest() method starts at the element itself, then the anchestors (parent, grandparent, ...) until a match is found. The closest() method returns null() if no match is found.
Try .next()
instead of .closest()
that traverses through the ancestors of the DOM element.
Working Demo
Also you should use $(this)
rather than $('.Level2')
else it'll select ALL the .Level2
rather than the clicked one.
You can also go for something like this - $(this).closest('.wrap').find('.Level3').fadeToggle();
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With