Can I reference the <li> index?
Can I reference the <li> index? I want to do this in order to be able to add / remove / reorder <li> tags without having to manually change the reference number.
Here is an example with some compiled HTML that describes how I think this might work:
<ol> <li>...</li> <li ref="some-ref">Some text that I want to refer to later ...</li> <li>...</li> <li>According to <liref ref="some-ref" />, ...</li> </ol> Of course, the desired result:
- ...
- Some text I want to talk about later ...
- ...
- According to 2., ...
Is there something similar in real HTML?
HTML does not provide such a mechanism. For this you need server or client scripts.
You can also try using the CSS counter properties: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Counters
For what it's worth, I accomplished what I wanted using jQuery. He does not answer the question directly, but may be useful to someone. It also works for nested lists.
Take this example:
<ol> <li>...</li> <li>Nested list <ol> <li>...</li> <li id="ref1">Some text that I want to refer to later ...</li> <li>...</li> <li id="ref2">Different text that I want to refer to ...</li> <li>According to <span class="ref" name="#ref2"></span>, ...</li> </ol> </li> <li>According to <span class="ref" name="#ref1"></span>, ...</li> </ol> Using this jQuery code:
$(function() { $('.ref').each(function() { var refLi = $($(this).attr('name')); var refLiAncestorLis = refLi.parents('li'); var reference = ''; for (var i = refLiAncestorLis.length - 1; i >= 0; i--) { reference += $(refLiAncestorLis[i]).index() + 1 + '.'; } reference += refLi.index() + 1 + '.'; $(this).text(reference); }); }); You can get this output:
- ...
- Nested list
- ...
- Some text I want to talk about later ...
- ...
- Another text I want to refer to ...
- According to 2.4., ...
- According to 2.2., ...