I have the following html structure
<div>
text 1
<div>
text 2
<div>
text 3
<div>
text 4
</div>
</div>
</div>
</div>
with the following jquery
$('div').hover(
function() {
$(this).addClass("hover");
},
function() {
$(this).removeClass("hover");
}
);
When I hover to the last div with text 4, all the above div elements will get the class hover.
Is there a clever way to only put the hover class on the last hovered div element? So when I hover to text 3 only the surrounding div wil get the hover class.
I don’t want to wrap the text in a new element since the applied situation is a little more complex than this. I also can not use CSS3.
On mouse over, add the class to the current element, then remove the class from all its ancestor
divs using.parents():On mouse out, remove the class from the current element and add the class to its parent
divusing.parent(), if its parent is one. This way, when the mouse moves from the currentdivto its parentdiv, it’ll receive the hover effect:The selector that you use in
.parents()and in.parent()must be the same selector that you use with$()so you don’t affect the wrong elements.jsFiddle preview