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?
Have you tried:
I think the problem you are facing is that
nextreturns the very next sibling, whereasnextAllreturns a collection of all the subsequent siblings matching your selector. Applying the:firstselector to yournextAllfilter 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: