Home  >  Article  >  Web Front-end  >  How to Retrieve the Applied Style Values of a DOM Element

How to Retrieve the Applied Style Values of a DOM Element

Susan Sarandon
Susan SarandonOriginal
2024-10-20 07:12:01910browse

How to Retrieve the Applied Style Values of a DOM Element

Retrieving the Display Property of a DOM Element

In a web page, the display property determines the visibility and layout of an element. The .style.* properties provide access to the style attributes defined in the HTML, while the getComputedStyle() method reveals the applied style values.

Understanding the .style.* Properties

The .style.* properties, such as .style.display, return the value of the corresponding style attribute assigned to an element. However, these properties do not reflect the browser's applied styles. For instance, in the following code snippet:

<code class="html"><style type="text/css">
  a { display: none; }
</style>

<script type="text/javascript">
  var a = (document.getElementById('a')).style;
  alert(a.display); // Displays an empty string
</script></code>

The .style.display property of the "a" element returns an empty string because there is no display attribute defined in the HTML. This is misleading since the element is visually set to display: none in the CSS style sheet.

Using getComputedStyle() for Applied Style Values

To retrieve the applied style values, use the getComputedStyle() method. For example:

<code class="javascript">var a = document.getElementById('a');
var computedStyle = window.getComputedStyle(a);
alert(computedStyle.display); // Displays "none"</code>

In this scenario, getComputedStyle() returns the actual CSS value applied to the "a" element.

Conclusion

When dealing with style properties, be aware of the distinction between the style attributes (accessed via .style.) and the applied style values (accessed via getComputedStyle()). The .style. properties only reflect the style attributes defined in the HTML, which may not accurately represent the element's visual appearance. For that purpose, always use getComputedStyle() to obtain the applied style values.

The above is the detailed content of How to Retrieve the Applied Style Values of a DOM Element. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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