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!