How to Access Computed Styles with JavaScript When Inline Styles Override Master Stylesheet Settings?

Mary-Kate Olsen
Release: 2024-11-06 17:05:02
Original
954 people have browsed it

How to Access Computed Styles with JavaScript When Inline Styles Override Master Stylesheet Settings?

Accessing Style from Master Stylesheet with JavaScript

When setting the display property of a div to "none" in a master stylesheet and attempting to access it via JavaScript using myDiv.style.display, you may encounter a blank return value. This is because there is a distinction between inline styles and computed styles.

Inline styles are set directly on the HTML element itself, while computed styles are a combination of all the styles applied to an element, including those set in external stylesheets or parent elements. When an inline style is present, it overrides any conflicting computed style.

When you access the style property of an element via JavaScript, you are only able to read the inline styles. Therefore, if you set the display property to "none" in the master stylesheet but have an inline style that overrides it, myDiv.style.display will return an empty string.

To access the computed style, you need to use the getComputedStyle() function. This function returns an object that contains all the computed styles for an element, including those set in external stylesheets or parent elements.

Here's an example of how to use getComputedStyle() to retrieve the computed display property:

var display = getComputedStyle(myDiv).display;
Copy after login

By using getComputedStyle(), you can access the computed style of an element, even if it has been overridden by an inline style.

The above is the detailed content of How to Access Computed Styles with JavaScript When Inline Styles Override Master Stylesheet Settings?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template