jQuery .css() to Return Object of Computed Styles

This article explains how to retrieve multiple computed CSS properties as a single JavaScript object using jQuery's .css() method. By passing an array of property names to .css(), developers can efficiently extract and interact with computed styles formatted as key-value pairs.

The Array Syntax

To get an object of computed styles, pass an array of style property strings to the jQuery .css() method:

var styles = $("#elementId").css(["width", "height", "color", "background-color"]);

When you pass a single string (e.g., $("#elementId").css("width")), jQuery returns a single string value. When you pass an array of strings, jQuery returns a plain JavaScript object containing the specified properties and their resolved values.

Example Output

Given a standard div element:

const computedStyles = $("#box").css([
  "width",
  "height",
  "display",
  "backgroundColor"
]);

console.log(computedStyles);

The returned object will resemble the following structure:

{
  "width": "300px",
  "height": "150px",
  "display": "block",
  "backgroundColor": "rgb(255, 0, 0)"
}

Important Considerations

  • Property Naming: You can use either camelCase (e.g., "backgroundColor") or kebab-case (e.g., "background-color"). The returned object's keys will match the casing you provided in the input array.
  • Computed Values: The returned values are computed by the browser, meaning relative measurements like percentages or em units are typically converted to absolute pixel values, and named colors are converted to rgb() or rgba() notation.
  • Target Elements: If the selector matches multiple elements, .css() only retrieves the computed styles for the first element in the matched set.
  • jQuery Version Support: The array argument syntax for .css() was introduced in jQuery 1.9.