Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery closest class selector

<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/

like image 903
olo Avatar asked Apr 17 '13 03:04

olo


People also ask

How do I get the closest div using jQuery?

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.

How do you target a class in jQuery?

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.

How do you use nearest?

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.


1 Answers

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();.

like image 147
Rishabh Avatar answered Sep 20 '22 20:09

Rishabh