getComputedStyle

The getComputedStyle method is a built-in JavaScript function that retrieves the computed styles of an HTML element. This includes styles provided by the browser, styles applied via style sheets, and properties set through the style attribute. The method returns an object containing the computed style of an element, allowing access to the final styles applied.

Usage

The primary use of getComputedStyle is to obtain the computed style interface of an element, which can then be used to access the final styles applied to that element. This is particularly useful when you need to know the exact style properties that are being rendered, as they may differ from those specified in the CSS due to cascading rules, inheritance, or browser defaults.

Example: Fetching Computed Style Values

Below is a simple example demonstrating how to fetch computed style values using the getComputedStyle method.

Listing 12.8. Fetching computed style values

<style>
  div {
    background-color: #ffc; display: inline; font-size: 1.8em;
    border: 1px solid crimson; color: green;
  }
</style>
<div style="color:crimson;" id="testSubject" title="Ninja power!">    #A
  忍者パワー
</div>
<script>
  function fetchComputedStyle(element,property) {                     #B
    const computedStyles = getComputedStyle(element);                 #C
    if (computedStyles) {                                             #D
      property = property.replace(/([A-Z])/g,'-$1').toLowerCase();
      return computedStyles.getPropertyValue(property);
    }
  }
  document.addEventListener("DOMContentLoaded", () => {
    const div = document.querySelector("div");
    report("background-color: " +
           fetchComputedStyle(div,'background-color'));               #E
    report("display: " +
           fetchComputedStyle(div,'display'));
    report("font-size: " +
           fetchComputedStyle(div,'fontSize'));
    report("color: " +
           fetchComputedStyle(div,'color'));
    report("border-top-color: " +
           fetchComputedStyle(div,'borderTopColor'));
    report("border-top-width: " +
           fetchComputedStyle(div,'border-top-width'));
  });
</script>
#A - Creates a test subject with a style attribute
#B - Defines a function that will get the computed value of a style property
#C - Uses the built-in getComputedStyle method to obtain a descriptor object
#D - Replaces camel-case notation with dashes
#E - Tests that we can obtain the values of various style properties, using different notations

Explanation

  1. Setup: We define a div element with inline styles and a style sheet that provides additional style rules. This setup allows us to test the computed styles resulting from both immediate and applied styles.

  2. Function Definition: The fetchComputedStyle function is defined to retrieve the computed value of a style property. It uses the getComputedStyle method to obtain a descriptor object of the element's styles.

  3. Property Name Adjustment: Before fetching the property value, the function adjusts the property name to the dashed version expected by the getPropertyValue method. This is done using a regular expression to replace camel-case notation with dashes and convert the string to lowercase.

  4. Fetching Values: The function is tested by fetching various style properties of the div element, demonstrating the ability to handle both camel-cased and dashed property names.

By using getComputedStyle, developers can accurately determine the styles being applied to elements, which is crucial for dynamic styling and debugging CSS issues.