The StylePropertyMapReadOnly
interface of the CSS Typed Object Model API provides a read-only representation of a CSS declaration block that is an alternative to CSSStyleDeclaration
. Retrieve an instance of this interface using Element.computedStyleMap()
.
We have to have an element to observe:
<p>
This is a paragraph with some text. We can add some CSS, or not. The style map
will include all the default and inherited CSS property values.
</p>
<dl id="output"></dl>
We add a touch of CSS with a custom property to better demonstrate the output:
p {
--someVariable: 1.6em;
--someOtherVariable: translateX(33vw);
--anotherVariable: 42;
line-height: var(--someVariable);
}
We add JavaScript to grab our paragraph and return back a definition list of all the default CSS property values using Element.computedStyleMap()
.
const myElement = document.querySelector("p");
const stylesList = document.querySelector("#output");
const stylePropertyMap = myElement.computedStyleMap();
for (const [prop, val] of stylePropertyMap) {
const cssProperty = document.createElement("dt");
cssProperty.innerText = prop;
stylesList.appendChild(cssProperty);
const cssValue = document.createElement("dd");
cssValue.innerText = val;
stylesList.appendChild(cssValue);
}