With the following code below I want to be able to apply a CSS style to the parent li class="parent" item in the list. But only when the user is hovering over the child li class="child" items for that particular parent.
It’s my understanding that this won’t be possible using just CSS, but does anyone know of a potential Javascript solution (ideally using jQuery, as we’re already using this library on our website)
Thanks!
<ul>
<li class="parent"><a href="URL" >Main Link</a>
<ul class="sub-menu">
<li class="child"><a href="URL" >Link</a></li>
</ul>
</li>
</ul>
You heard right—CSS doesn’t allow you to traverse upward on the DOM tree, only downward. As in, you can select children, but not parents.
Here’s one method to do it with jQuery:
What we do is select the
lielement with the classchild. We bind thehoverevent to it and fire a function when that event occurs. The function finds the closest parent of the childliwith the classparent, and we change its CSS.More on
on()here,closest()here, andcss()here.Also keep in mind that for earlier versions of jQuery, you can use
bind()ordelegate().EDIT: To have it change on mouseover and mouseout:
And what you do here is define the class
myClassin your CSS.toggleClassadds the class if it doesn’t already exist on the element and removes it otherwise. It’s self explanatory. This way, you save a few bytes and use more preferred and recommended jQuery.