Akanksha Maurya
Akanksha Maurya

Reputation: 35

hasClass is not working on mouse hover

Hello I am trying to find that class "toggle-nav" contains "dropdown" or not , but hasClass is not working.

My code is here:

<li class="toggle-nav">
    <ul class="dropdown">
        <li><a href="#">Add User</a></li>
        <li><a href="#>">User List</a></li>
    </ul>
</li>
<li class="toggle-nav">
    <ul class="dropdown">
        <li><a href="#">Add Admin</a></li>
        <li><a href="#>">Admin List</a></li>
    </ul>
</li>
<li class="toggle-nav1"><a href="#">Setting</a></li>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $(".toggle-nav").hover(function() {
            console.log($(this).hasClass("dropdown"));
        });
    });
</script>

Upvotes: 1

Views: 627

Answers (3)

Haresh Vidja
Haresh Vidja

Reputation: 8496

$(this) is pointing to only hovered element and hasClass check existance of class on $(this). So you have to use $("ul",this).hasClass("dropdown") instead of $(this).hasClass("dropdown") for check in child element.

    $(document).ready(function() {
        $(".toggle-nav").hover(function() {
            console.log($("ul",this).hasClass("dropdown"));
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<ul>
<li class="toggle-nav">
    <ul class="dropdown">
        <li><a href="#">Add User</a></li>
        <li><a href="#>">User List</a></li>
    </ul>
</li>
<li class="toggle-nav">
    <ul class="dropdown">
        <li><a href="#">Add Admin</a></li>
        <li><a href="#>">Admin List</a></li>
    </ul>
</li>
<li class="toggle-nav1"><a href="#">Setting</a></li>
</ul>

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You would need to use find:

$(".toggle-nav").hover(function() {
            console.log($(this).find(".dropdown").length);
        });

and then you can check with if statement if length is greater than 0 the class exists inside toggle-nav

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

That is because class dropdown exists in child element and not targeted element. You need to look for class in child elements. if length of returned set is greater than 0, child element with class dropdown exists:

 $(".toggle-nav").hover(function() {
   console.log($(this).find(".dropdown").length > 0);
 });

Upvotes: 1

Related Questions