When an element’s styles come from several places, its computed style gives you the values applied after those sources are evaluated. getComputedStyle(element) returns an interface for querying them, including styles from browser defaults, stylesheets, inline attributes, script changes, and inheritance. section 12.3 section 12.3.3
To read a particular CSS property:
- Call getComputedStyle(element), then use its getPropertyValue method with a CSS property name such as background-color. section 12.3.3
- A helper can normalize camel-case input such as backgroundColor to the dashed form; cache the returned interface rather than needlessly calling getComputedStyle again. 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>
A styled div demonstrates fetching computed values, including background-color and display. section 12.3.3
