Home >Web Front-end >CSS Tutorial >Why Does `element.style` Return Empty Values When CSS Styles Are Defined in a Separate File?
Understanding CSS Style Properties in JavaScript
When referencing CSS style properties in JavaScript, developers often encounter an unexpected issue: element.style returning empty values despite defining styles in the CSS file. This article aims to shed light on this behavior and explain why it occurs.
The Difference Between Inline and Computed Styles
JavaScript's element.style property provides access to inline styles defined directly within an HTML element. However, when CSS styles are defined separately in a CSS file, they are not considered inline styles. Instead, they become computed styles.
Computed Styles: The Applied Values
Computed styles represent the actual style properties applied to an element after considering all inherited styles, CSS rules, and browser default values. To access computed styles in JavaScript, use the getComputedStyle() function.
Explanation of Empty element.style Values
element.style holds inline styles only. Since CSS styles are not defined inline, they are not accessible through element.style and thus return empty values.
Example:
<div>
#test { display: block; }
console.log(document.getElementById('test').style.display); // Returns ""
Using getComputedStyle to Retrieve Computed Styles
To obtain the applied style properties, including those defined in CSS, use getComputedStyle():
console.log(window.getComputedStyle(document.getElementById('test')).display); // Returns "block"
The above is the detailed content of Why Does `element.style` Return Empty Values When CSS Styles Are Defined in a Separate File?. For more information, please follow other related articles on the PHP Chinese website!