When accessing the style property of an HTML element, using the syntax this.style[property], it's important to note that it only returns styles directly applied to the element itself. Styles inherited from external stylesheets or computed from cascading rules are not included.
In the provided code snippet:
function css(prop, value) { if (value == null) { // retrieve style return this.style[prop]; // returns an empty string } // set style }
Calling element.css("height") will return an empty string because the height style is defined in the external stylesheet. The inline style applied to the element (background: #CCC) is not relevant here.
To retrieve the effective value of a style, including those inherited or computed, use the getComputedStyle() function:
const style = getComputedStyle(element); console.log(style.height); // returns "100px"
The above is the detailed content of Why Does `this.style[property]` Return an Empty String for Inherited Styles?. For more information, please follow other related articles on the PHP Chinese website!