25
Jun
2012

How to add a new CSS class using jQuery

Posted in: jQuery , No Comments

jquery_logo
In previous tutorial we learned how to add a css property using jQuery.

Instead of adding a CSS property we should prefer adding a CSS class. This will make things easy. So, in this tutorial I will show you how to add a new CSS class to any selected ID / Class.

Step 1:
Write some text under a ID newclass

<div id="newclass">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</div>

At this stage our page looks like this:

Step 2:
Add a new class red in our CSS style.

.red {
color: red;
font-weight: bold;
}

Step 3:
Add jQuery library in head section.

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

Step 4:
Now we will add jQuery code in head section and tell it to find ID newclass and add a new class red to it.

<script type="text/javascript">
$(document).ready(function(){
$("#newclass").addClass('red');
});
</script>

Done!!!
So, our page will look like this:


You can now see that the text color changed to red and font weight changed to bold.
This is because in class red we defined new color and font-weight.

About the Author

Name: Ravi Shekhar
I love learning and sharing web stuffs.

Share this post

Twitter Facebook Google Buzz Digg StumbleUpon Delicious Technorati

Leave a Reply