Thomas H
Thomas H

Reputation: 902

jquery selector for selected siblings of a common parent

I have a menu structure as follows:

<li><a href="#" class="navCars">Cars</a><img src="images/navbar-menu-divider.png" class="divider"></li>
<li><a href="#" class="navTrucks">Trucks <img src="images/navbar-menu-down-arrow.png/"></a><img src="images/navbar-menu-divider.png" class="divider"></li>
<li><a href="#" class="navBoats">Boats <img src="images/navbar-menu-down-arrow.png/" class="menu_arrow"></a><img src="images/navbar-menu-divider.png" class="divider"></li>

For the Trucks and Boats items which support a dropdown, I need to change the .divider images to the left and right of a given menu item on mouse over. I've tried this selector to grab the right side:

$( ":parent .divider", this ).attr( "src", "images/navbar-menu-hover-right.png" );

Which doesn't seem to work. To get the left side, I need to go up a level, find the previous sibling, then get its .divider (though I'm sure there are several alternatives).

Any help from jquery magicians appreciated!

Upvotes: 1

Views: 407

Answers (3)

Dmitri Farkov
Dmitri Farkov

Reputation: 9691

Here we go.

$("~ .divider", this)

should grab the sibling of the element which is in this case .divider.

If you know for sure that the sibling (.divider) is right next to your dom element you can do

$("+ .divider", this)

Difference between + and ~ is: + only selects the immediate sibling, ~ selects any of the latter siblings.

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227310

You can try .closest().

$(this).closest('li').find('.divider').attr("src","images/navbar-menu-hover-right.png");

Upvotes: 1

Adam Albrecht
Adam Albrecht

Reputation: 6870

There is a .siblings helper

$("...").siblings(".divider")

Upvotes: -1

Related Questions