LearnFast.Ninja

Change class jQuery

In this example you will see how we changing the class of Html element with jQuery attr function. After click event we change the class to a new class with new style.

Main idea: Use the attr function to override the current class.
$('.MyButton').attr('class''NewClass');

Working example code:

<!DOCTYPE html>

<html>

<head>

    <title>Untitled Page</title>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

    <style type="text/css">

        .MyButton

        {

            padding10px;

            color#333;

            border-radius4px;

            background#c0c0c0;  

        }

       

        .NewClass

        {

            padding10px;

            color#333;

            border-radius4px;

            background#ccffcc;  

        }

    </style>

</head>

<body>

    <br />

    <span class="MyButton" onclick="$('.MyButton').attr('class', 'NewClass');">

        Button

    </span>

</body>

</html>


Result:
Before:


After click:


Tags

jquery

class attr