How to change CSS using jQuery?

By |April 12th, 2016|Categories: CSS, jQuery|Tags: , , , |

The jQuery .css method is used to GET or SET DOM element CSS properties.

The following tutorial will demonstrate 4 core concepts of jQuery’s .css method

      1. GET a CSS property from a DOM element
      2. GET multiple CSS properties from a DOM element
      3. SET a CSS property on DOM elements
      4. SET multiple CSS properties on DOM elements

When looking to GET a CSS property with jQuery’s .css method, jQuery will return the first matched element’s CSS properties. So, you will want to pay close attention to the jQuery selector used when requesting a CSS property. If you pass a class into the selector and a group of elements gets returned, jQuery’s .css method will only show CSS properties for the first matched element in the group of matched elements.

Let’s start by taking a look at using jQuery’s .css method to GET a CSS property from a DOM element with a class of box. In this first example, let’s create a <div> with a solid background color

Next, let’s use jQuery’s .css method to GET the opacity of the <div>

Note: jQuery’s .css method returns the CSS value as a string, not a number

To return multiple CSS properties, pass in an array of CSS properties. Passing in an array of CSS properties will return an object with CSS key:”value” pairs

Next, let’s take a look at how to set CSS properties with jQuery. When looking to SET CSS properties, all matched elements returned by the selector will have the css properties defined SET. Setting properties with jQuery’s .css method makes updating a large group of html elements easy. You could update all of paragraph tags in your docuemnt with just one line of code.

Finally, setting multiple css properties with jQuery can be done by passing in a javascript object. The key is name of the css property, and the value will be the css value. A good practice is to enclose the keys within quotes to avoid errors with certain css properties such as background-color which has a hyphen between background and color.

To summarize, jQuery’s .css method makes getting and setting css properties with javascript convenient and easy. Whether you are looking to get the font size of some text, or set the width and height of an html element, jQuery’s .css method is a great addition to your tool set. One detail to note when getting a css property, is the css values will get returned as a string. However, when setting a css property such as opacity, width, height, etc.. the .css method conveniently accepts strings or numbers. When setting multiple css properties, a good practice is to wrap your javascript’s object keys in single or double quotes.

DJ Rosenbaum
Independent Author and Coder.