Retrieving and Setting CSS Properties in jQuery
In this jQuery tutorial, Mytour will further guide you on retrieving and setting CSS properties in jQuery. Additionally, readers can explore other lessons on Mytour to learn more about inserting content into HTML documents using jQuery.
1. jQuery's css() method
2. Retrieving CSS property values
3. Setting a single CSS property and value for elements
4. Setting multiple CSS properties and values for elements
1. jQuery's css() method
The css() method in jQuery is used to retrieve the computed value of a CSS property or to set one or more CSS properties for the selected elements.
By using this method, we can directly apply styles to HTML elements (inline styles) that haven't been applied or are difficult to determine in the stylesheet.
2. Retrieving CSS Property Values
To obtain the computed value of a CSS property for an element, we use the property name as a parameter for the css() method.
The basic syntax looks like the following:
$(selector).css('propertyName');
Example: In the following example, we will retrieve and display the computed value of the CSS background-color property of the div element when clicked:
The output result looks like this:
3. Setting a Single CSS Property and Value for Elements
The css() method in jQuery can take the name and value of a property as separate parameters to set a unique CSS property for elements.
The basic syntax looks like the following:
$(selector).css('propertyName', 'value');
Example: In the following example, it illustrates how to set the CSS property background-color for div elements to the value red when clicked:
The output result looks like this:
4. Setting Multiple CSS Properties and Values
Additionally, we can use the css() method to set multiple CSS properties.
The basic syntax for setting multiple properties for elements looks like the following:
Example: The following example demonstrates how to set the CSS properties background-color and padding for multiple selected elements simultaneously:
The output result looks like this:
In this tutorial, Mytour has just guided you on how to retrieve and set CSS properties using the css() method in jQuery. In the next lesson, Mytour will further introduce you to how to adjust the size of elements in jQuery. If you have any doubts or questions, readers can leave their opinions in the comments section below the article.