Getting and Setting CSS Attributes

The css() method is very much like the attr() method, but it works with the CSS styles of an element rather than the HTML attributes of the element. When querying style values, css() returns the current style (or “computed style”) of the element: the returned value may come from the style attribute or from a stylesheet. Note that it is not possible to query compound styles such as “font” or “margin”. You must instead query individual styles such as “font-weight”, “font-family”, “margin-top”, and “margin-left”. When setting styles, the css() method simply adds the style to the element’s style attribute. css() allows you to use hyphenated CSS style names (“background-color”) or camel-case JavaScript style names (“backgroundColor”). When querying style values, css() returns numeric values as strings, with the units suffix included. When setting, however, it converts numbers to strings and adds a “px” (pixels) suffix to them when necessary:

$("h1").css("font-weight"); // Get font weight of 1st <h1> $("h1").css("fontWeight"); // Camel case works, too $("h1").css("font"); // ERROR: can't query compound style $("h1").css("font-variant", // Set style on all <h1> tags "smallcaps"); $("div.note").css("border", // Okay to set compound styles "solid black 2px"); // Set multiple styles at once $("h1").css({ backgroundColor: "black", textColor: "white", fontVariant: "small-caps", padding: "10px 2px 4px 20px", border: ...

Get jQuery Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.