Home  >  Article  >  Web Front-end  >  Can JavaScript Access the Value of Invalid Custom CSS Properties?

Can JavaScript Access the Value of Invalid Custom CSS Properties?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 07:09:01638browse

Can JavaScript Access the Value of Invalid Custom CSS Properties?

Accessing Invalid Custom CSS Properties from JavaScript

In CSS, custom properties can be defined using the -- prefix. However, can you access the value of invalid or custom CSS properties from JavaScript?

Question:

Given the following CSS:

<code class="css">div {
    -my-foo: 42;
}</code>

Can you later in JavaScript determine the value of the -my-foo property for a particular div element?

Answer:

Accessing invalid property names in CSSStyleDeclaration doesn't seem to be supported in popular browsers like Chrome and Firefox. For the given CSS, the CSSStyleDeclaration object contains only the valid property width and skips -my-foo.

Interestingly, the DOM-Level-2 Style spec states that all specified properties should be available through the CSSStyleDeclaration interface. There might be some browser that supports this behavior.

DIY Approach:

As a workaround, you can parse the raw CSS text using document.getElementsByTagName("style")[0].innerText. However, this can be a cumbersome approach.

The above is the detailed content of Can JavaScript Access the Value of Invalid Custom CSS Properties?. 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