.css ( "class_names" | "style_json" )
.style() function is very handy when we want to style an element with single property at a time. To do multiple style property changes, style() has to be called repeatedly. and Also .style() will not attach css classes to elements.
These limitations can be overcome by using .css(). .css() helps to attach or remove css classes to or from an element. it also helps to apply multiple style changes all at a time.
Parameters
Example 1
This example shows how to attach and remove a CSS class to the source element. simple class name or preceding with "+" will attach the class to element. Class names with preceding "-" will remove the class from element.
JS
HTML
CSS
$.domLoaded(function() { $.get("#btn1").on("click", function() { // Attach big_red and text classes $.get("#box1").css("big_red text"); }); $.get("#btn2").on("click", function() { // Remove thick_border class $.get("#box1").css("-thick_border"); }); });
Result
Example 2
Adding or Removing CSS classes can be clubbed together as 'space' separated list and provided as input. Following example attaches two classes and removes one class.
JS
HTML
CSS
$.domLoaded(function() { $.get("#btn1").on("click", function() { // Attach thick_border, text and remove big_red class simultaneously $.get("#box1").css("+thick_border +text -big_red"); }); });
Result
Example 3
Sometimes there may be a need for applying multiple styles and no scope for using a CSS class. css() can apply multiple styles to an element. The style should be given as name value pairs in JSON. Following example applies multiple styles to div element.
JS
HTML
CSS
$.domLoaded(function() { $.get("#btn1").on("click", function() { // Attach multiple styles $.get("#box1").css({ "background-color" : "red", "border" : "10px solid #000", "width" : "200px", "height" : "100px" }); }); });
Result
| ||||||||||||||||