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

CSS Custom Properties

DOM Level 2 style

As pointed out by Anurag, this was something proposed in DOM Level 2 and later deprecated. Internet Explorer was the only browser that implemented it and they stopped supporting it in Edge. IE expects that the property doesn't start with a dash so my-foo: 42; should work.

CSS variables style

Newer browsers support CSS variables. These start with a double dash: --my-foo: 42; (they can be reused elsewhere like this font-size: var(--my-foo);)

Example

CSS

div {
  --my-foo: 42;
  my-foo: 42;
}

JS

// Chrome 49, Firefox 31, Safari 9.1 (future Edge):
const cssVariable = bodyStyles.getPropertyValue('--my-foo')
// IE:
const cssCustomProperty = bodyStyles['my-foo']

Browser Support

Currently Microsoft Edge is the only browser with no support for either of these methods, but as of writing CSS variables in Edge are "under active development".


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:

document.getElementsByTagName("style")[0].innerText

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.

Tags:

Javascript

Css