tags:

views:

64

answers:

2

Assume I have the following CSS:

div {
    -my-foo: 42;
}

Can I later in JavaScript somehow know what the value of the -my-foo CSS property is for a given div?

+1  A: 

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.

Anurag
@Anurag, very interesting, especially the part about the DOM spec saying that custom properties should be exposed in CSSStyleDeclaration. I found that Mozilla has a bug for this, and I would encourage you and others here who are interested in this to voice their opinion and vote for this bug. I also added a comment to the bug, better explaining the scenario in which I would like to use this. https://bugzilla.mozilla.org/show_bug.cgi?id=116694
Alessandro Vernet
A: 

Why do you want to reference an invalid style? Are you just using this as a storage medium?

If so, you can use jQuery's data() function to store arbitrary data for elements that match a given CSS selector.

E.g.

$('div').data('my-foo', '42');

Matt
@Matt, this is not to store data, but to use CSS in an AOP kind of way. Assume you have 3 parties: a "widgets author", a "framework author", and "application author" who uses the widgets in an app. The widget authors defines the markup generated by the widgets, and the application author can't change this markup. But it can change the way it looks by adding CSS, and he could, also with CSS if I could use custom properties, influence how the framework behaves (in addition to how the browser behaves).
Alessandro Vernet
@Matt, if you'd like to have more details on this one, also see the comment I posted to this Mozilla bug: https://bugzilla.mozilla.org/show_bug.cgi?id=116694
Alessandro Vernet