- How to get CSS styles from an element with JavaScript
- You might also like.
- Window: getComputedStyle() method
- Syntax
- Parameters
- Return value
- Throws
- Examples
- HTML
- CSS
- JavaScript
- Result
- Description
- defaultView
- Use with pseudo-elements
- Notes
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- HTMLElement: style property
- Value
- Examples
- Getting style information
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
How to get CSS styles from an element with JavaScript
In JavaScript, sometimes, you might want to retrieve CSS styles applied to an element through inline styles or external style sheets. There are multiple ways to do this, depending on whether you fetch inline styles or rendered styles.
In vanilla JavaScript, the DOM style property is used to get the styles applied to an HTML element using the style attribute. Let us say we have the following HTML element:
button id="clickMe" style="color: red; font-weight: bold;">Click Mebutton>
const btn = document.getElementById('clickMe') // pint color & font weight properties console.log(btn.style.color) // red console.log(btn.style.fontWeight) // bold
However, the style property only works for the inline styles defined using the style attribute. If you try to access a property not defined as an inline style rule, let us say the backgroundColor , a null value will be returned:
console.log(btn.style.backgroundColor) // null
The style property can not be used to retrieve style information from elsewhere, such as the style rules defined using the
To get the actual CSS property values used to render an HTML element, you can use the getComputedStyle() method. This method works for everything: inline styles, external style sheets, and browser defaults. Let us say you have the following embedded
style> button background-color: yellow; text-align: center; height: 20px; width: 100px; > style>
The getComputedStyle() method is always called on the window object with the element as a parameter and returns an object of properties:
const btn = document.getElementById('clickMe') // get all rendered styles const styles = window.getComputedStyle(btn)
Now you can access any CSS property like you’d have done with the style property. For example, to access the background-color , you can do the following:
const backgroundColor = styles.backgroundColor // rgb(255, 255, 0)
To get the rendered height and width of the element regardless of whether or not it was defined, use the following code:
const height = styles.height // 20px const width = styles.width // 100px
Alternatively, you can use the getPropertyValue() method on the styles object to access a CSS property. It accepts the actual name of the CSS property and not the one used for JavaScript:
const fontWeight = styles.getPropertyValue('font-weight') // 700
Note: The value 700 is equivalent to bold for the CSS property font-weight . Similarly, rgb(255, 255, 0) is just an RGB value which is the same as yellow .
The getComputedStyle() method is used to get the actual CSS properties used by the browser to render the element. It works in all modern and old browsers, including IE 9 and higher. Finally, the getComputedStyle() method only works for getting styles. You can not use it to set a specific style to an HTML element. To set CSS properties, you should always use the DOM style property, as explained in an earlier article.
CSS pseudo-elements are extremely useful to style parts of an element without additional HTML elements. To get style information from pseudo-elements, you pass in the name of the pseudo-element as a second argument to the getComputedStyle() method. Let us say we have the following
element:
p class="tip">Learn JavaScrit for free!p>
.tip::first-letter color: green; font-size: 22px; >
To retrieve the color property of the .tip::first-letter , you should use the following JavaScript code snippet:
const tip = document.querySelector('.tip') // retrieve all styles const styles = window.getComputedStyle(tip, '::first-letter') // get color console.log(styles.color) // rgb(0, 128, 0)
- The DOM style property to retrieve inline styles applied to an element using the style attribute.
- The window.getComputedStyle() method to retrieve computed styles applied to an element through elements and external style sheets. To get pseudo-elements CSS styles, you need to pass the name of the pseudo-element as a second parameter.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
Window: getComputedStyle() method
The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.
Individual CSS property values are accessed through APIs provided by the object, or by indexing with CSS property names.
Syntax
getComputedStyle(element) getComputedStyle(element, pseudoElt)
Parameters
The Element for which to get the computed style.
A string specifying the pseudo-element to match. Omitted (or null ) for real elements.
Return value
A live CSSStyleDeclaration object, which updates automatically when the element’s styles are changed.
Throws
If the passed object is not an Element or the pseudoElt is not a valid pseudo-element selector or is ::part() or ::slotted() .
Note: Valid pseudo-element selector refers to syntactic validity, e.g. ::unsupported is considered valid, even though the pseudo-element itself is not supported. Additionally, the latest W3 standard explicitly supports only ::before and ::after , while the CSS WG draft does not restrict this value. Browser compatibility may vary.
Examples
HTML
CSS
p width: 400px; margin: 0 auto; padding: 20px; font: 2rem/2 sans-serif; text-align: center; background: purple; color: white; >
JavaScript
const para = document.querySelector("p"); const compStyles = window.getComputedStyle(para); para.textContent = `My computed font-size is $compStyles.getPropertyValue("font-size")>,\n` + `and my computed line-height is $compStyles.getPropertyValue( "line-height", )>.`;
Result
Description
The returned object is the same CSSStyleDeclaration type as the object returned from the element’s style property. However, the two objects have different purposes:
- The object from getComputedStyle is read-only, and should be used to inspect the element’s style — including those set by a element or an external stylesheet.
- The element.style object should be used to set styles on that element, or inspect styles directly added to it from JavaScript manipulation or the global style attribute.
The first argument must be an Element . Non-elements, like a Text node, will throw an error.
defaultView
In many code samples, getComputedStyle is used from the document.defaultView object. In nearly all cases, this is needless, as getComputedStyle exists on the window object as well. It’s likely the defaultView pattern was a combination of folks not wanting to write a testing spec for window and making an API that was also usable in Java.
Use with pseudo-elements
getComputedStyle can pull style info from pseudo-elements (such as ::after , ::before , ::marker , ::line-marker — see the pseudo-element spec).
style> h3::after content: " rocks!"; > style> h3>Generated contenth3> script> const h3 = document.querySelector("h3"); const result = getComputedStyle(h3, ":after").content; console.log("the generated content is: ", result); // returns ' rocks!' script>
Notes
- The returned CSSStyleDeclaration object contains active values for CSS property longhand names. For example, border-bottom-width instead of the border-width and border shorthand property names. It is safest to query values with only longhand names like font-size . Shorthand names like font will not work with most browsers.
- CSS property values may be accessed using the getPropertyValue(propName) API or by indexing directly into the object such as obj[‘z-index’] or obj.zIndex .
- The values returned by getComputedStyle are resolved values . These are usually the same as CSS 2.1’s computed values , but for some older properties like width , height , or padding , they are instead the same as used values . Originally, CSS 2.0 defined the computed values as the «ready to be used» final values of properties after cascading and inheritance, but CSS 2.1 redefined them as pre-layout, and used values as post-layout. For CSS 2.0 properties, getComputedStyle returns the old meaning of computed values, now called used values. An example difference between pre- and post-layout values includes the resolution of percentages for width or height , as those will be replaced by their pixel equivalent only for used values.
- Returned values are sometimes deliberately inaccurate. To avoid the «CSS History Leak» security issue, browsers may lie about the computed styles for a visited link, returning values as if the user never visited the linked URL. See Plugging the CSS History Leak and Privacy-related changes coming to CSS :visited for examples of how this is implemented.
- During CSS transitions, getComputedStyle returns the original property value in Firefox, but the final property value in WebKit.
- In Firefox, properties with the value auto return the used value, not the value auto . So if you apply top:auto and bottom:0 on an element with height:30px and a containing block of height:100px , Firefox’s computed style for top returns 70px , as 100 − 30 = 70.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 17, 2023 by MDN contributors.
Your blueprint for a better internet.
HTMLElement: style property
The read-only style property of the HTMLElement returns the inline style of an element in the form of a live CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned only for the attributes that are defined in the element’s inline style attribute.
Shorthand properties are expanded. If you set style=»border-top: 1px solid black» , the longhand properties ( border-top-color , border-top-style , and border-top-width ) are set instead.
This property is read-only, meaning it is not possible to assign a CSSStyleDeclaration object to it. Nevertheless, it is possible to set an inline style by assigning a string directly to the style property. In this case the string is forwarded to CSSStyleDeclaration.cssText . Using style in this manner will completely overwrite all inline styles on the element.
Therefore, to add specific styles to an element without altering other style values, it is generally preferable to set individual properties on the CSSStyleDeclaration object. For example, you can write element.style.backgroundColor = «red» .
A style declaration is reset by setting it to null or an empty string, e.g., elt.style.color = null .
Note: CSS property names are converted to JavaScript identifier with these rules:
- If the property is made of one word, it remains as it is: height stays as is (in lowercase).
- If the property is made of several words, separated by dashes, the dashes are removed and it is converted to camelCase: background-attachment becomes backgroundAttachment .
- The property float , being a reserved JavaScript keyword, is converted to cssFloat .
The style property has the same priority in the CSS cascade as an inline style declaration set via the style attribute.
Value
Examples
Getting style information
The following code snippet demonstrates how the values obtained using the element’s style property relates to the style set on the HTML attribute:
doctype html> html lang="en-US"> body style="font-weight:bold"> div style="border-top: 1px solid blue; color:red" id="elt"> An example div div> pre id="out">pre> body> html>
const element = document.getElementById("elt"); const out = document.getElementById("out"); const elementStyle = element.style; // We loop through all styles (for…of doesn't work with CSStyleDeclaration) for (const prop in elementStyle) if (Object.hasOwn(elementStyle, prop)) out.textContent += `$ elementStyle[prop] > = '$elementStyle.getPropertyValue(elementStyle[prop])>'\n`; > >
Note font-weight is not listed as a value for elementStyle as it is not defined within the style attribute of the element itself. Rather, it is inherited from the definition on its parent. Also note that the shorthand border-top property, defined in the style attribute, is not listed directly. Rather, it is replaced by the three corresponding longhand properties ( border-top-color , border-top-style , and border-top-width ).
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 7, 2023 by MDN contributors.
Your blueprint for a better internet.