最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - add class to li on hover but remove from all others - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Jul 24, 2015 at 8:54 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Jul 24, 2015 at 8:49 user3181912user3181912 951 silver badge7 bronze badges 1
  • 2 Kindly post your HTML structure – user1608841 Commented Jul 24, 2015 at 8:51
Add a ment  | 

5 Answers 5

Reset to default 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");
    });

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./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>

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

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

Use above code

发布评论

评论列表(0)

  1. 暂无评论