Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jquery next() to select next div by class

Tags:

I'm fairly new to jquery and struggling with something that should be fairly simple. I want to select the previous and next div with class "MenuItem" from the div with class "MenuItemSelected".

HTML

<div id="MenuContainer" class="MenuContainer">     <div id="MainMenu" class="MainMenu">         <div class="MenuItem">             <div class="MenuItemText">Menu Item #1</div>             <div class="MenuItemImage">images/test1.jpg</div>         </div>             <div class="MenuDividerContainer">             <div class="MenuDivider"></div>         </div>         <div class="MenuItem MenuItemSelected">             <div class="MenuItemText">Menu Item #2</div>             <div class="MenuItemImage">images/test2.jpg</div>         </div>         <div class="MenuDividerContainer">             <div class="MenuDivider"></div>         </div>         <div class="MenuItem">             <div class="MenuItemText">Menu Item #3</div>             <div class="MenuItemImage">images/test3.jpg</div>         </div>     </div><!--/ .MainMenu --> </div><!--/ .MenuContainer --> 

Here is the jquery for next that I thought should have worked.

$('div.MenuItemSelected').next('.MenuItem'); 

I also tried

$('div.MenuItemSelected').nextAll('.MenuItem'); 

The only thing i could get to work is

$('div.MenuItemSelected').next().next(); 

That seems hokey, any ideas?

like image 646
Ryan Sampson Avatar asked Nov 16 '09 16:11

Ryan Sampson


People also ask

How to get next div in jQuery?

jQuery next() Method The DOM tree: This method traverse forward along the next sibling of DOM elements. Related methods: nextAll() - returns all next sibling elements of the selected element. nextUntil() - returns all next sibling elements between two given arguments.

Which jQuery method is used to set one or more style properties to the selected element?

jQuery css() Method The css() method sets or returns one or more style properties for the selected elements.


1 Answers

Have you tried:

$('div.MenuItemSelected').nextAll('.MenuItem:first'); 

I think the problem you are facing is that next returns the very next sibling, whereas nextAll returns a collection of all the subsequent siblings matching your selector. Applying the :first selector to your nextAll filter should make things right.

I would like to point out, that if the structure of your markup is consistent (so it's always guaranteed to work), then your current solution might (benchmark, benchmark, benchmark) well be the faster way:

$('div.MenuItemSelected').next().next(); 
like image 135
karim79 Avatar answered Sep 28 '22 18:09

karim79