liveBook · Manning

getPropertyValue

As explained in Secrets of the JavaScript Ninja, Second Edition

A CSSStyleDeclaration method that retrieves the computed value of a specified CSS property.

To check what style an element will actually use, call getPropertyValue on the style interface returned by getComputedStyle(element). It retrieves a computed value for a CSS property, using CSS names such as font-size or background-color—not JavaScript-style camel case. section 12.3.3

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>

This example fetches computed values and converts camel-cased names to dashed CSS names before calling getPropertyValue. section 12.3.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains the method’s role, accepted property-name format, and use through a helper function.
Examples
Uses background-color and display queries, with a helper that converts camel-cased property names.
What you can do after
Apply getComputedStyle and getPropertyValue to retrieve an element’s computed CSS property value.
How it connects
Connects computed styles with getComputedStyle, inline styles, and CSS style sheets.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.