The value of a CSS counter on an element cannot be queried directly. One has to jump through loops, querying the stylesheets and searching for previous DOM nodes to re-calculate it (or copy the logic from CSS to the JS file).
CSSOM should attend to it. The Element
interface should therefore be extended like this:
partial interface Element {
Integer getCounterValue(DOMString counterName);
};
The method
element.getCounterValue('counter-name')
returns the value of the countercounter-name
at the position ofelement
in the DOM. If no counter with this name exists, the method returns0
. (This is in sync with the specced behavior for non-existing counters.)
Example:
<body>
<h2>Foo</h2>
<p>Bar</p>
</body>
/* stylesheet: */
h2 { counter-increment: foo; }
Then the following holds:
document.querySelector('body').getCounterValue('foo') === 0;
document.querySelector('h2').getCounterValue('foo') === 1;
document.querySelector('p').getCounterValue('foo') === 1;
document.querySelector('p').getCounterValue('non-existing') === 0;
Use case
One use case is cross-referencing figures. If <figure>
elements increment a counter and display it in the <figcaption>
, it would be great to auto-generate references on other positions in the document, like see fig. 4
, much like LaTeX’s \ref{figure}
.
<figure id="foo">
<img src="getCounterValue_enhances_workflow.png" alt="Proof for thesis">
<figcaption>Labeled with :before { content: "Fig. " counter(figure); }</figcaption>
</figure>
<p>See <a href="#foo">the figure above</a> for a more detailed image.</p>
^---- replace with "figure 4"