Cover Image for jQuery css() method
111 views

jQuery css() method

The jQuery css() method is used to get or set CSS properties for selected elements. It allows you to retrieve the current value of a CSS property or set a new value for one or more CSS properties dynamically.

The syntax for using the css() method is as follows:

To Get the Value of a CSS Property:

$(selector).css(propertyName);

To Set a New Value for a CSS Property:

$(selector).css(propertyName, value);
  • selector: It is a string that specifies the elements to be selected.
  • propertyName: It is a string representing the name of the CSS property you want to get or set.
  • value: It is a string representing the new value you want to set for the CSS property. If you omit this parameter, the css() method will act as a getter and return the current value of the specified CSS property.

Here’s an example of how you can use the css() method:

HTML:

<div id="myDiv" style="width: 200px; height: 100px; background-color: red;"></div>

JavaScript:

// Get the current width of the div element
var width = $('#myDiv').css('width');
console.log('Current Width: ' + width);

// Set a new background color for the div element
$('#myDiv').css('background-color', 'blue');

In the example, the css() method is used to get the current width of the div element with the ID “myDiv” using $('#myDiv').css('width'). The current width value is then logged to the console.

Then, the css() method is used again to set a new background color of “blue” for the same div element using $('#myDiv').css('background-color', 'blue').

The css() method can be used to manipulate various CSS properties, such as width, height, background color, font size, etc. It is commonly used when you want to dynamically change the appearance or layout of elements based on user interactions or other events.

Keep in mind that the css() method directly modifies the inline CSS of the selected elements. If you want to apply styles from a CSS class, it is generally recommended to use the addClass() and removeClass() methods instead to add or remove classes, which will handle the styling through external CSS rules. This promotes separation of concerns and improves code maintainability.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS