🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

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.
DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
Udemy
Pros
  • Easy to navigate
  • No technical issues
  • Seems to care about its users
Main Features
  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

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.