Code has been added to clipboard!

Making jQuery Change a CSS Property or Return Its Value

Reading time 2 min
Published Jan 18, 2018
Updated Oct 2, 2019

jQuery Change CSS: Main Tips

  • The jQuery .css() returns the value of a CSS property applied to an element.
  • You can also use it to make jQuery change a CSS property for a selected element.
  • To learn more about the methods used in jQuery to modify CSS properties, see this tutorial.

Retrieving Property Values with .css()

In its simplest form, jQuery .css() method retrieves the CSS properties and values of the selected elements. To return the existing property values, follow this syntax:

$(selector).css(propertyName);

As you can see, the only argument you need to include is the name of the CSS property you are interested in. In the code example below, an alert pops up as you click the button, and the text color value of the heading element is returned:

Example
$("button").click(() => {
    alert($("h1").css("color"));
});

Making jQuery Change a CSS Property

To make jQuery change a CSS property value, the syntax is very similar - you just need to add the new value for the selected property to adopt. Depending on a property, it can be specified in either a string or a number:

$(selector).css(propertyName, newValue);

To modify multiple properties at once, add the parameters in pairs:

$(selector).css({propertyName:newValue, propertyName:newValue, ...});

In the example below, you can see how you can make jQuery change background color and text color in a <div> element using jQuery .css():

Example
$("div").css({
  "color": "white", 
  "background-color": "green"
});

Tip: you can combine jQuery .css() with .animate() to create visual effects.

Latest Coupon Found:

Verified STAFF PICK

TOP-RATED CODING COURSES

Learn the skills of tomorrow

The best time to learn programming is now - follow this link to access 100+ coding courses and enjoy learning at a very low cost!

Expiration date: 13/05/2021
2287 People Used
Only 92 Left
Rating
5.0