Home > Web Front-end > CSS Tutorial > Why Does `this.style[property]` Return an Empty String for Inherited Styles?

Why Does `this.style[property]` Return an Empty String for Inherited Styles?

DDD
Release: 2024-12-04 10:37:12
Original
189 people have browsed it

Why Does `this.style[property]` Return an Empty String for Inherited Styles?

Understanding the Empty String Return of this.style[property]

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
}
Copy after login

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.

How to Retrieve Computed Style Information

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"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template