Home  >  Article  >  Web Front-end  >  How to Retrieve Values of Invalid/Custom CSS Properties in JavaScript?

How to Retrieve Values of Invalid/Custom CSS Properties in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 07:12:30334browse

How to Retrieve Values of Invalid/Custom CSS Properties in JavaScript?

Accessing Values of Invalid/Custom CSS Properties in JavaScript

When defining custom or invalid CSS properties like "-my-foo", developers may wonder if it's possible to retrieve their values from JavaScript.

To answer this question, let's assume we have CSS as shown below:

div {
    -my-foo: 42;
}

Attempting to access the value of "-my-foo" from JavaScript via the CSSStyleDeclaration object may result in difficulties. Tests in both Chrome and Firefox show that these browsers skip invalid properties and only expose valid ones. For instance, with CSS like:

div {
    width: 100px;
    -my-foo: 25px;
}

the CSSStyleDeclaration object will only contain the following keys:

0: width
cssText: "width: 100px"
length: 1

Therefore, obtaining the value of "-my-foo" from JavaScript using this method is not feasible.

However, the DOM-Level-2 Style specification states that "an implementation [browser] is expected to provide access to all specified properties... through the CSSStyleDeclaration interface." This suggests that browsers should theoretically list invalid properties in the object, even if they don't recognize them.

As a workaround, it's possible to parse the raw CSS text to retrieve the value of the custom property. However, this approach is not recommended as it involves significant effort and may not always be reliable or efficient.

The above is the detailed content of How to Retrieve Values of Invalid/Custom CSS Properties in JavaScript?. 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