Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 56 ยท Manipulating the DOM

CSS and Classes

Read and change styles with jQuery: the .css() getter and setter, computed values, addClass, removeClass, toggleClass with state, hasClass, and why classes win.

Changing how something looks is one of the most common jobs in a script: highlight a row, mark a field as invalid, open a menu. jQuery gives you two tools for it. .css() reads and writes individual style values, and the class methods (.addClass(), .removeClass(), .toggleClass(), .hasClass()) switch whole groups of styles on and off by name.

Both work, but they are not equal. By the end of this lesson you will know why experienced developers reach for classes first and keep .css() for values that can only be known at run time.

Two ways to style

.css() One property at a time, written inline.
Classes A named bundle of styles from your stylesheet.

Classes keep looks in CSS and logic in JavaScript.

1 / 2

Reading styles with .css()

With one argument, .css() returns the computed value of that property for the first element. Computed means the final value the browser is using after all stylesheets, classes and inline styles have been applied; it is not limited to the style attribute.

JavaScript
$("h1").css("color");        // "rgb(30, 64, 175)"
$("h1").css("fontSize");     // "32px"
$("h1").css("font-size");    // "32px" (the dashed name works too)

Notes on the values you get back:

  • Colors are normalized to rgb(...) or rgba(...), even if the stylesheet used #1e40af or blue.
  • Lengths are returned in pixels, for example "32px", even if the stylesheet used 2rem. Use parseFloat() when you need the number.
  • Read longhand properties such as margin-top rather than the shorthand margin, because shorthand results are not consistent across browsers.
  • An element that is not rendered (for example inside a display: none parent) has computed values, but its layout numbers may not be meaningful.

Writing styles with .css()

Pass two arguments to set one property on every element in the collection, or an object to set several at once:

JavaScript
$(".card").css("background-color", "#fef9c3");
$(".card").css({
  backgroundColor: "#fef9c3",
  "border-radius": "8px",
  padding: 12
});

Both naming styles work: backgroundColor (camelCase, like the DOM's style object) and "background-color" (dashed, like CSS). In an object literal, the dashed form needs quotes. A plain number is turned into pixels for properties that take lengths, so padding: 12 becomes 12px, while unitless properties such as opacity and zIndex stay as numbers.

You can also use relative values to nudge a number, and a function to compute each element's value:

JavaScript
$("#box").css("left", "+=20px");           // move 20px right of where it is now
$(".bar").css("width", function (i, current) {
  return parseFloat(current) * 1.5;        // 50% wider
});

To remove an inline value that you set earlier, assign an empty string: .css("color", ""). The element then falls back to whatever the stylesheet says.

Reading and writing with .css()

Working with classes

Classes are the cleaner way to change appearance, because the actual style rules stay in your CSS file where designers expect them. Your script only decides which state an element is in.

JavaScript
$("#menu").addClass("open");
$("#menu").addClass("open animated");        // several names, space separated
$("#menu").removeClass("open");
$("#menu").removeClass();                    // remove ALL classes
$("#menu").hasClass("open");                 // true or false (first element)

.addClass() and .removeClass() also accept a function that returns the class names for each element, based on its index and current classes.

toggleClass and state

.toggleClass("name") adds the class if it is missing and removes it if present. Even more useful is the second argument, a boolean state: true forces the class on, false forces it off. This lets you drive a class from a condition without writing if/else:

JavaScript
$("#save").toggleClass("disabled", form.isInvalid);
$("li").toggleClass("even", (index % 2) === 0);

Compare it with the clumsy alternative of checking hasClass first and then adding or removing. The state form is shorter and can never get out of sync. See also the property toggling in Attributes and Properties for real element state such as disabled.

Classes and toggleClass with state

Getting the number out of a CSS value

.css() returns strings such as "32px" or "0.5". To do arithmetic you need the number, and parseFloat() is the right tool because it stops at the first character that is not part of the number.

JavaScript
var size = parseFloat($("h1").css("font-size"));   // 32
$("h1").css("font-size", (size * 1.25) + "px");    // 40px

.css() also accepts relative strings, so for growing or shrinking you can skip the parsing: $("h1").css("font-size", "+=4") adds four pixels. For element sizes prefer .width() and .height(), which already return numbers (see dimensions). Use parseFloat() for anything that can have decimals, such as line-height or opacity. A computed value of "auto" or "normal" gives NaN, so check with Number.isNaN() when the value might not be numeric.

Parse, change, write back

Smoothly changing a background image

CSS cannot animate between two background-image values: the switch is instant. The standard trick is to fade one layer out while another fades in. Put two absolutely positioned layers in a container, load the new image into the hidden layer, give it the visible class, and remove that class from the old one. A CSS transition: opacity does the fading, and jQuery only changes the images and the classes.

Crossfading background images

Preload large images (new Image().src = url) first so the fade does not start on a blank layer.

Which to use: classes or .css()

Prefer classes whenever the look can be described in advance. They keep your CSS in one place, they respect media queries, hover states and transitions, they are easy to override, and they do not leave style attributes scattered across the page.

Use .css() when the value is computed from data and cannot exist in a stylesheet:

  • A progress bar width of 63% calculated from numbers.
  • A tooltip placed at the mouse position.
  • A color picked by the user.

A good pattern combines both: a class for the state, and .css() or a CSS variable only for the dynamic part. For example, .css("--accent", userColor) sets a custom property while the stylesheet decides where it is used.

Finally, remember that inline styles beat most stylesheet rules because of CSS specificity. If you set .css("color", "red") and later a class tries to change the color, the class will lose. Another reason to avoid inline styles for anything that can toggle.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A stylesheet gives an element font-size: 2rem. What does $(el).css("fontSize") return?

    .css() getter returns the computed value, in pixels for lengths, regardless of the unit used in the stylesheet.
  2. 2. Which line turns the class active ON for an element only when the variable isOpen is true, and OFF otherwise?

    toggleClass with a boolean second argument forces the class on or off according to that state.
  3. 3. Why should you prefer classes over .css() for a highlight style?

    Classes separate presentation from behavior and avoid the specificity problems that inline styles cause.
  4. 4. How do you remove an inline style you set earlier with .css("color", "red")?

    Assigning an empty string clears the inline value so the stylesheet applies again.

Summary

  • .css("prop") returns the computed value of the first element; colors come back as rgb() and lengths in pixels.
  • .css("prop", value) or .css({ ... }) sets styles on all elements; camelCase and dashed names both work.
  • Numbers become pixels for length properties, "+=20px" is relative, and "" clears an inline value.
  • .addClass(), .removeClass() and .hasClass() manage class names; .toggleClass(name, state) follows a condition.
  • Use classes for predictable looks and .css() for values calculated at run time.
  • Inline styles win in specificity, so overusing .css() makes later overrides harder.

Next, learn how to measure and position elements in Dimensions, Position and Scrolling.