JQuery Operation CSS
JQuery has several methods for working with CSS. We will study the following:
- AddClass ()-adds one or more classes to the selected element
- Removeclass ()-deletes one or more classes from the selected element
- Toggleclass ()-switch operation to add/Remove classes for selected elements
- CSS ()-Set or return style properties
Instance style sheet
The following style sheet will be used for all the examples on this page:
. Important{font-weight:bold;font-size:xx-large;}. Blue{color:blue;}
JQuery addclass () method
The following example shows how to add a class attribute to different elements. Of course, when you add a class, you can also select multiple elements:
Instance
$ ("button"). Click (function () { $ ("H1,h2,p"). AddClass ("Blue"); $ ("div"). AddClass ("important");});
You can also specify multiple classes in the AddClass () method:
Instance
$ ("button"). Click (function () { $ ("#div1"). AddClass ("Important blue");
JQuery Removeclass () method
The following example shows how to remove the specified class attribute from a different element:
Instance
$ ("button"). Click (function () { $ ("H1,h2,p"). Removeclass ("Blue");});
JQuery Toggleclass () method
The following example shows how to use the JQuery Toggleclass () method. This method toggles the Add/Remove class for the selected element:
Instance
$ ("button"). Click (function () { $ ("H1,h2,p"). Toggleclass ("Blue");});
jquery-css () method
The CSS () method sets or returns one or more style properties for the selected element.
Return to CSS Properties
To return the value of the specified CSS property, use the following syntax:
CSS ("PropertyName");
The following example returns the Background-color value of the first matching element:
Instance
$ ("P"). CSS ("Background-color");
Set CSS Properties
To set the specified CSS properties, use the following syntax:
CSS ("propertyname", "value");
The following example sets the Background-color value for all matching elements:
Instance
$ ("P"). CSS ("Background-color", "yellow");
Set multiple CSS properties
To set multiple CSS properties, use the following syntax:
CSS ({"PropertyName": "Value", "PropertyName": "Value",...});
The following example sets Background-color and font-size for all matching elements:
Instance
$ ("P"). css ({"Background-color": "Yellow", "font-size": "200%"});
jquery manipulating HTML elements (getting and setting CSS classes)