Search code examples
javascriptjquerycsshovermouseenter

add class to li on hover but remove from all others


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.


Solution

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