tags:

views:

244

answers:

2

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>

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?

Thanks.

+4  A: 

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();
karim79
Thanks!! However it only works without the space between .MenuItem and :firstEG: $('div.MenuItemSelected').nextAll('.MenuItem:first')
Aros
@Aros - my bad, fixed it in the answer. Hope that didn't have you running in circles for too long :)
karim79
A: 

Have you tried: .parent() and .children() ? http://docs.jquery.com/Traversing

Achilles