jQuery

jQuery Add CSS to Div Examples

If you have always wondered how to add CSS using jQuery, then this article is a must read. In this article, I am going share very easy way to add CSS to a DIV or any element using jQuery. Read on to find out more.

Examples to Add CSS to DIV using jQuery

To demonstrate on how to add CSS to Div or any other element in a web page, here is an example. I have a div with ID “my_div”. I have declared 3 classes in my stylesheet, green, red and blue. The green class makes the text color green. Red class applies red background color to the div and the blue class applies blue border to the div. So far, I applied two classes to the Div. Now I want to add the red class upon body load so that the background color turns to red.

Example: Add css to div when button is clicked using jQuery

<html>
<head>
<title>jQuery Add CSS to Div or any element</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<style type="text/css">
.green {
color:#090;
}
.red {
background-color: #F00;
color:#FFF;
}
.blue {
padding: 5px;
border: 2px solid #09F;
}
</style>
</head>

<body>

<div id="my_div" class="green blue">This is my div with multiple css. We are adding "red" class on page load.</div>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){

$("#my_div").addClass('red');

});
</script>

</body>
</html>

In the above, if you comment the jQuery code and view the page, you will notice that the green text color & blue border are applied, whereas when the code is uncommented, it adds red background color.

So that’s how you use jQuery to add CSS to Div or any other element.

Simple, isn’t it?

Do you know of any other ways to add CSS to Div or any other element using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*