Home > Web Front-end > JS Tutorial > body text

How to Retrieve the Applied Style Values of a DOM Element

Susan Sarandon
Release: 2024-10-20 07:12:01
Original
906 people have browsed it

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

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

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!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!