sidewinder
sidewinder

Reputation: 3163

Selecting an element whose parent element does not have a particular class

Assuming, I have the following HTML:

<ul class="topnav">
    <li class=""><a href="/">Page 1</a></li>
    <li class=""><a href="/Page2/">Page 2</a></li>
    <li class=""><a href="/Page3/">Page 3</a></li>
    <li class=""><a href="/Page4/">Page 4</a></li>
    <li class=""><a href="/Page5/">Page 5</a></li>
    <li class="active"><a href="/Page6/">Page 6</a></li>
</ul>

When the mouse leaves the LI element, it is suppose change the color of the font back to grey except for the A element whose parent LI has a class value of 'active'.

Below is the JQuery code I am trying: (The 'mouseleave' function is not working)

        $(".top_nav li a").mouseenter(
            function() {
                $(this).stop().animate({'color': '#ffffff'}, 'slow');
        });

        $(".top_nav li a").mouseleave(
            function() {
                $(this).parent().not(".active").stop().animate({'color': '#a5acb2'}, 'slow');
        });

Upvotes: 2

Views: 1127

Answers (3)

karim79
karim79

Reputation: 342635

Try using .hasClass():

if($(this).parent().hasClass("active")) {
    $(this).stop().animate({'color': '#a5acb2'}, 'slow');
}

If your list items can only be assigned the one class, you can do this:

// class not equals 'active'
$(this).parent("[class!='active']");

Otherwise, this should work:

// class contains 'active'
$(this).parent("[class*='active']");

Upvotes: 2

jimy
jimy

Reputation: 4908

$(".top_nav li a").hover(  function () {

    $(this).stop().animate({'color': '#ffffff'}, 'slow');

  }, 

  function () {

    $(this).parent().not(".active").stop().animate({'color': '#a5acb2'}, 'slow');

  });

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816302

$(this).parent() selects the li element and all other functions apply to this one instead to the a element.

You can do:

$(this).not(".active > a").stop()...

DEMO

Upvotes: 2

Related Questions