LearnFast.Ninja

jQuery change css class property

Suppose you have class in your html page that you want to change its property using jQuery, how to do this is very simple. The main idea is to use the css method with the css property as parameter. Look what we done in our code and try the example. Create class style. Then create elements, and place your class in some of them. Create function that change the css class background color.

Step 1: create class style

.My_Class {

    background-color: #C0C0C0;

}


Step 2: create elements, place your class in some of them

<h1 class="My_Class">jQuery change css class property</h1>

<div>

    This is a tutorial about

    <span class="My_Class">jQuery</span>

</div>


Step 3: create function that change the css class background color

function Change_Class_BG(Class_Name, color) {

    $("." + Class_Name).css({ "background-color": color });

}


The main idea is: 

$(".My_Class").css({ property : value_of_property};


Complete code:

<html>

<head>

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

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

    <style type="text/css">

        .My_Class {

            background-color: #C0C0C0;

        }

    </style>

    <script type="text/javascript">

        function Change_Class_BG(Class_Name, color) {

            $("." + Class_Name).css({ "background-color": color });

        }

    </script>

</head>

<body>

    <h1 class="My_Class">jQuery change css class property</h1>

    <div>

        This is a tutorial about

 <span class="My_Class">jQuery</span>

    </div>

    <input type="button" value="Change My_Class BG" onclick="Change_Class_BG('My_Class', '#EEE');" />

</body>

</html>


Tags

jquery

jquery-tutorial-for-beginners