3

I need to add a class to an li on hover but remove the same class from all other lis in the list (this is for a nav).

The code I have so far is:

jQuery(".navcontent").on('mouseenter', 'li', function() {
    if (jQuery('.childmenu', this)) {
        jQuery('.childmenu', this).addClass("child-active");
    } else {
        jQuery('.navcontent li .childmenu').removeClass("child-active");
    }
});

I can't quite work out what I need to do...

Any help would be much appreciated.

Tushar
  • 85,780
  • 21
  • 159
  • 179
user3181912
  • 95
  • 1
  • 7

5 Answers5

3

You have alternative ways to do that:

  1. first remove class of all the elements and add one you want:
    jQuery(".navcontent li").on('mouseenter', function() {
        jQuery('.childmenu').removeClass("child-active");
        jQuery('.childmenu', this).addClass("child-active");
    });
  1. if they are siblings, you can use siblings:
    jQuery(".navcontent li").on('mouseenter', function() {
        jQuery('.childmenu', this).addClass("child-active")
          .siblings('.childmenu').removeClass("child-active");
    });
Pete
  • 57,112
  • 28
  • 117
  • 166
Panwen Wang
  • 3,573
  • 1
  • 18
  • 39
2

Please check the code below

jQuery(".navcontent li").on('mouseenter', function(event) {
  jQuery('.navcontent li').removeClass("child-active");
  jQuery(this).addClass("child-active");

});
.child-active {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<ul class="navcontent">
  <li>Links</li>
  <li>Links</li>
  <li>Links</li>
  <li>Links</li>
  <li>Links</li>
</ul>
Tushar
  • 85,780
  • 21
  • 159
  • 179
w3debugger
  • 2,097
  • 19
  • 23
0
jQuery(".navcontent li").on('mouseenter', function(event) {
    jQuery('.navcontent li .childmenu').removeClass("child-active");
    jQuery(event.target).addClass("child-active");

});
Tushar
  • 85,780
  • 21
  • 159
  • 179
jrath
  • 980
  • 4
  • 14
0
jQuery(".navcontent li").on('mouseover', function() {
    jQuery(".navcontent li .childmenu").removeClass('child-active');
    jQuery(this).addClass('child-active');
});

Use above code

Tushar
  • 85,780
  • 21
  • 159
  • 179
user1608841
  • 2,455
  • 1
  • 27
  • 40
0
jQuery(".navcontent li").on('mouseenter', function() {
    jQuery(".navcontent li").removeClass("child-active");
    jQuery(this).addClass("child-active");
});
MazzCris
  • 1,812
  • 1
  • 14
  • 20