About
To get the computed values of a style for an HTML element, you use the browser webapi window.getComputedStyle.
Part of the calculation of values depends on the formatting algorithm appropriate for the target media type (display).
For example, if the target medium is the screen, user agents apply the visual formatting model.
Example
Get by name
Retrieving the display
<h1>Article Title</h1>
let title = document.querySelector('h1');
let display = window.getComputedStyle(title).getPropertyValue('display');
console.log('The display of the heading h1 is :'+display);
Get all by index
- The HTML
<h1>Title</h1>
<p>Below in the log container, you can see all default computed style of the browser for the title.
- The snippet to retrieve all computed style declaration for the element h1
let title = document.querySelector('h1');
let styles = window.getComputedStyle(title);
for(var i = 0; i < styles.length; i++){
attributeName = styles.item(i);
value = styles .getPropertyValue(attributeName);
console.log(attributeName+" : "+value);
}
With Computed Style Map
- The HTML
<h1 style="border: 1px solid blue; width: fit-content; padding: 1rem">Title</h1>
- The Javascript that will lookup the border
let borderDeclaration = document
.querySelector("h1")
.computedStyleMap()
.get('border')
.toString()
console.log(`The border declaration is: ${borderDeclaration}`)
- The result: