LearnFast.Ninja

jQuery change css class name

Build two class names styles. Build your custom HTML elements and mark them with ID. Build function for handled the class change. Get the current class name. Remove the current class. Add the new class. Test the complete code example.

Step 1: Build two class names styles: 

.First {

    background-color: #c0c0c0;

    color: #333333;

    cursor: pointer;

}
 

.Second {

    background-color: #000000;

    color: #FFFFFF;

}

 
Step 2: Build your custom HTML elements and mark them with ID: 

<div id="My_Div" class="First" onclick="ChangeClass('Second');">

    Hello from change css class name.

</div>

 
Step 3: Build function for handled the class change: 
function ChangeClass(New_Class) {
}
 
Step 4: Get the current class name: 
var Old_Class = $("#My_Div").attr('class');
 
Step 5: Remove the current class: 
("#My_Div").removeClass(Old_Class);
 
Step 6: Add the new class: 
$("#My_Div").addClass(New_Class);
 
Complete code: 

<html>

<head>

    <title>jQuery change css class name</title>

 

    <style type="text/css">

        .First {

            background-color: #c0c0c0;

            color: #333333;

            cursor: pointer;

        }

 

        .Second {

            background-color: #000000;

            color: #FFFFFF;

        }

    </style>

 

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>

 

    <script type="text/javascript">

        function ChangeClass(New_Class) {

            var Old_Class = $("#My_Div").attr('class'); 

  

            // jQuery TheBestData.com jQuery change css class name

            $("#My_Div").removeClass(Old_Class);

            $("#My_Div").addClass(New_Class);

        }

    </script>

</head>

<body>

    <div id="My_Div" class="First" onclick="ChangeClass('Second');">

        Hello from change css class name.

    </div>

</body>

</html>



Tags

jquery

class css