I generate the numbering of my headers and figures with CSS's counter
and content
properties:
img.figure:after {
counter-increment: figure;
content: "Fig. " counter(section) "." counter(figure);
}
This (appropriate browser assumed) gives a nice labelling "Fig. 1.1", "Fig. 1.2" and so on following any image.
Question: How can I access this from Javascript? The question is twofold in that I'd like to access either the current value of a certain counter (at a certain DOM node) or the value of the CSS generated content (at a certain DOM node) or, obviously, both information.
Background: I'd like to append to links back-referencing to figures the appropriate number, like this:
<a href="#fig1">see here</h>
------------------------^ " (Fig 1.1)" inserted via JS
As far as I can see, it boils down to this problem:
I could access content
or counter-increment
via getComputedStyle
:
var fig_content = window.getComputedStyle(
document.getElementById('fig-a'),
':after').content;
However, this is not the live value, but the one declared in the stylesheet. I cannot find any interface to access the real live value. In the case of the counter, there isn't even a real CSS property to query.
Edit: Digging deeper and deeper through the DOM specs, I found the DOM Level 2 Style Counter interface. This seems to a) allow access to the current counter value and b) be implemented in Firefox, at least. However, I have no idea on how to use it. My current approach died tragically after this Firebug output:
// should return a DOM 2 Counter interface implementation...
window.getComputedStyle(fig_a_element, ':after')
.getPropertyCSSValue("counter-increment")[0]
.getCounterValue();
[Exception... "Modifications are not allowed for this document" code: "7"
nsresult: "0x80530007 (NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR)"
location: "http://localhost/countertest.html Line: 71"]
Any idea, how this could be brought to life would be highly appreciated.
Edit 2: Apparently I misinterpreted the Counter object of DOM Level 2 Style. It, too, has no property to return the current counter value. This makes the above approach invalid.
New approach: Is there a possibility to read the content of a pseudo-element via the DOM? That is, can I select the pseudo-element (treeWalker
comes to mind) and then get its nodeValue
? (If you start to type 'jQuery' now, please reconsider to change that term into 'Sizzle'...)