avernet avernet - 1 year ago 89
CSS Question

Can I access the value of invalid/custom CSS properties from JavaScript?

Assume I have the following CSS:

div {
-my-foo: 42;

Can I later in JavaScript somehow know what the value of the
CSS property is for a given

Answer Source

I don't think you can access invalid property names, at least it doesn't work in Chrome or Firefox for me. The CSSStyleDeclaration simply skips the invalid property. For the given CSS:

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

style:CSSStyleDeclaration object contains only the following keys:

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

However, interestingly this is what the DOM-Level-2 Style spec says:

While an implementation may not recognize all CSS properties within a CSS declaration block, it is expected to provide access to all specified properties in the style sheet through the CSSStyleDeclaration interface.

implying that the CSSStyleDeclaration object ought to have listed the -my-foo property in the above example. Maybe there is some browser out there which supports it.

The code I used for testing is at http://jsfiddle.net/q2nRJ/1/.

Note: You can always DIY by parsing the raw text. For example:


but that seems like a lot of work to me, and not knowing your reasons for doing this, I can't say if a better alternate for your problem exists.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download