How to use the hasClass() in JQ? also expain the toggleClasss() in JQuery.

Asked 28-Jul-2021
Viewed 324 times

1 Answer


1

The hashClass() method in Jquery checks whether the given class name is existing or not, if it is yes, then this function returns true, if it is not, it returns false. To make the website more responsive.

Syntax:
$(selector).hasClass(classname)

jQuery's toggleClass() method is used to add or remove one or more classes from selected elements. This toggleClass() automatically adds and removes classes. If the class is added then it is given class remove, If the class removed then it is given add number.

Syntax:
$(selector).toggleClass(classname)
$(selector).toggleClass(classname,function(index,currentclass),switch)

<!DOCTYPE html>  

<html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
<script>
    $(document).ready(function () {
        $('button').click(function () {
            alert('hasClass : '+ $('div').hasClass('panel'));
            $('div').toggleClass('panel');
            alert('hasClass : ' + $('div').hasClass('panel'));
        });
    });
</script>
<style>
    body {
    margin:10px;
    }
    .panel {
        box-sizing:border-box;
        padding:10px;
        background-color:red;
        color:white;
        font-size:45px;
        width:100%;
        height:auto;
        text-align:center;
    }
</style>
</head>
<body>
 <div >
     <h1>This is div by toggle effected </h1>
 </div><br />
<button>Click here </button>
</body>
</html>

How to use the hasClass() in JQ? also expain the toggleClasss() in JQuery.