JQuery hover over last element in hierarchy

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");
    }
);​

      

jsFiddle

When I am on the last div with text 4, all of the above divs get class hover.

Is there a sane way to just put the hover class on the last hovering div element? So when I hover the text over 3, only the surrounding div will have a hover class.

I don't want to wrap the text in a new element as the application situation is a little more complicated than that. I also cannot use CSS3.

+3


source to share


2 answers


Hover over, add a class to the current element, then remove the class from your ancestor div

with .parents()

:

    function() {
        $(this).addClass("hover").parents('div').removeClass("hover");
    },

      

Turning off the class from the current element and add it to the parent div

using .parent()

if its parent is one. Thus, when the mouse moves from the current div

to the parent div

, it will get a hover effect:



    function() {
        $(this).removeClass("hover").parent('div').addClass("hover");
    }

      

The selector you use in .parents()

and .parent()

must be the same selector you use with $()

so as not to affect the wrong elements.

JsFiddle preview

+6


source


You could do



$('div').hover(
    function() {
        $('div').removeClass("hover");
        $(this).addClass("hover");
    },
    function() {
        $(this).removeClass("hover");
    }
);​

      

0


source







All Articles