Add CSS to Div Using jQuery

Demo

Picking up jQuery skills as a developer is a must have in today’s development industry, and if you have any experience with JavaScript, then learning the jQuery syntax will come a lot faster and easier than one might think. This quick tutorial will show you how to add css to a div with jQuery.

Here is a our div:

<html>
 <head>
 <title>Adding CSS to a Div with jQuery - Tutorial - MDLoring.com</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 </head>
  <body>
   <div id="container">
    <p>Hello, this is the div we are going to change the CSS on</p>
     <button id="changeMe" onclick="changeMe()">Click Me!</button>
   </div>
  </body>
 </html>

Now we will build a JavaScript function so when we click the button, it will trigger the CSS div change with jQuery on the container div.

  <script type="text/javascript">
   function changeMe() {
     $("#container").css('border', '1px solid black');
     $("#container").css('border-radius', '5px');
     $("#container").css('padding', '10px');
     $("#container").css('font-size', '18px');
     $("#container").css('background', '#CCCCCC');
   }
  </script>
 

Here is the full code:

<html>
 <head>
 <title>Adding CSS to a Div with jQuery - Tutorial - MDLoring.com</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 </head>
  <body>
   <div id="container">
    <p>Hello, this is the div we are going to change the CSS on</p>
     <button id="changeMe" onclick="changeMe()">Click Me!</button>
   </div>

  <script type="text/javascript">
   function changeMe() {
      $("#container").css('border', '1px solid black');
      $("#container").css('border-radius', '5px');
      $("#container").css('padding', '10px');
      $("#container").css('font-size', '18px');
      $("#container").css('background', '#CCCCCC');
   }
  </script>
  </body>
 </html>

If you found this tutorial useful, then you should also check out my tutorial on how to toggle hide and show div with jQuery, along with hide and show html elements with jQuery.

Leave a Comment

Your email address will not be published. Required fields are marked *