开发者

jquery selector for selected siblings of a common parent

开发者 https://www.devze.com 2023-02-19 13:22 出处:网络
I have a menu structure as follows: <li><a href=\"#\" class=\"navCars\">Cars</a><img src=\"images/navbar-menu-divider.png\" class=\"divider\"></li>

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( "s开发者_开发知识库rc", "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!


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.


You can try .closest().

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


There is a .siblings helper

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号