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.
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
Coursera
Pros
  • Professional service
  • Flexible timetables
  • A variety of features to choose from
Main Features
  • Professional certificates of completion
  • University-level courses
  • Multiple Online degree programs
Datacamp
Pros
  • Great user experience
  • Offers quality content
  • Very transparent with their pricing
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

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 Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 27/01/2021
3176 People Used
Only 97 Left
Rating
5.0