jQuery addClass removeClass hasClass toggleClass

jQuery addClass , removeClass, hasClass,toggleClass

In this tutorial, we will explains how to manage the classes of DOM element.


Assume we have an element:

<div id="foo" class="tumble">Some text.</div>

when we add classes selected and hightlight to the element using jQuery addClass function. (#foo is the selector and $('#foo') is the matched DOM elements)

$('#foo').addClass("selected hightlight");

The Dom element would be changed to:

<div id="foo" class="tumble selected hightlight">Some text.</div>

Now ,it's easy to understand removeClass method which just remove the designated class from the selected DOM elements.

$('#foo').removeClass("hightlight");

the element would be:

<div id="foo" class="tumble selected">Some text.</div>

hasClass method will check if element has given class.

$( "#foo" ).hasClass( "selected" ) //true
$( "#foo" ).hasClass( "hightlight" ) //false ,we had remove it.

toggleClass method will Add or remove classes to/from matched elements.

The logic is:

if(hasClass){
  then remove class
}
else{
  add class
}

Assume,Now the element DOM is :

<div id="foo" class="tumble selected">Some text.</div>

The first time we apply $( "#foo" ).toggleClass( "hightlight" )to the div element ,we get the following:

<div class="tumble selected hightlight">Some text.</div>

The second time we apply $( "#foo" ).toggleClass( "hightlight" ), the element class is returned to:

<div class="tumble selected">Some text.</div>

jQuery addClass , removeClass, hasClass,toggleClass Examples


Press F12 to open Dev Tools,Click Elements Panel to observe the element's changes.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
    <div id="foo" class="tumble">Some text.</div>
    <script>
    $(function($){
        $('#foo').addClass("selected hightlight");

        // $('#foo').removeClass("hightlight");
        // console.log($( "#foo" ).hasClass( "selected" ));
        // $( "#foo" ).toggleClass( "hightlight" );
    });
    </script>
</body>
</html>
date2019-04-02 01:54:37 From:www.jquerypluginhub.com Author:JPH
Related Tags:
Comments

Leave a Reply

Your email address will not be published. Required fields are marked *