In Jquery there are the several methods to manipulate the CSS . Some of the useful css methods are given below
1. addClass(): add one or more css class to selected element.
2. removeClass() : remove one or more css class to selected element.
3. toggleClass(): Toggles between adding/removing classes from the selected elements
Sample code for addClass()
This method is used to add css class for given element.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <style type="text/css"> .bckColor { color:orange; font-size:20px; background-color:green; } .size { height:200px; width:400px; border:solid 1px; } </style> <script src="../../Scripts/jquery.min.js"></script> <script> $(function () { $("#btnSubmit").click(function () { $("div").addClass("bckColor"); }) }); </script> </head> <body> <div class="size"> <p>This is the sample text</p> </div> <button id="btnSubmit">Click here to change color</button> </body> </html>
In the above code we have used addClass() method to change the color of Div element.
Sample code for removeClass()
This method is used to remove css class name from given element.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <style type="text/css"> .bckColor { color:orange; font-size:20px; background-color:green; } .size { height:200px; width:400px; border:solid 1px; } .clear { } </style> <script src="../../Scripts/jquery.min.js"></script> <script> $(function () { $("#btnSubmit").click(function () { $("div").removeClass("bckColor size"); }) }); </script> </head> <body> <div class="bckColor size"> <p>This is the sample text</p> </div> <button id="btnSubmit">Click here to remove css class</button> </body> </html>
In the above example we have noticed that we are removing class name i.e bckColor and size from given div
toggleClass Method:
This method is used add and remove i.e toggle the css class from given element.
Sample code for toggleClass as given below
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <style type="text/css"> .bckColor { color:orange; font-size:20px; background-color:green; } .size { height:200px; width:400px; border:solid 1px; } </style> <script src="../../Scripts/jquery.min.js"></script> <script> $(function () { $("#btnSubmit").click(function () { $("div").toggleClass("bckColor"); }) }); </script> </head> <body> <div class="size"> <p>This is the sample text</p> </div> <button id="btnSubmit">Click here to change color</button> </body> </html>
Note: In the above code “bckColor” css class name will be add and remove on basis of button btnSumit click event.
One thought on “CSS manipulation in Jquery (part 8)”