jQuery css() Method
The jQuery css() method facilitates the manipulation of CSS properties for selected elements. It offers the ability to retrieve or update styling attributes, allowing for dynamic changes in appearance. Here are examples illustrating the usage of the css() method:
Getting CSS Property
Consider an HTML paragraph (<p>) element with a defined class:
To retrieve the value of a specific CSS property using jQuery:
Setting CSS Property
You can use the css() method to modify the value of a CSS property:
This will change the text color of the paragraph to blue.
Setting Multiple CSS Properties
To set multiple CSS properties at once, pass an object with property-value pairs:
In this case, both font size and line height of the paragraph will be updated.
The css() method can also calculate values, especially for numeric properties:
In this example, the width of the paragraph will increase by 50 pixels.
Chaining Multiple Properties
You can chain multiple css() calls to modify multiple properties sequentially:
This will set the font weight to bold and transform the text to uppercase.
The css() method offers a dynamic way to alter styling attributes, making it easy to create responsive and interactive designs. It's important to note that while css() is effective for one-time changes, for classes or repeated changes, applying and removing classes via addClass() and removeClass() may be a more structured approach.