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?
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.
jQuery css() Method The css() method sets or returns one or more style properties for the selected elements.
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();
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