Is it possible to refer to a <li> index?
Asked Answered
G

3

6

Is it possible to refer to a <li> index? I want to do that to be able to add/remove/reorder the <li> tags without having to manually change the reference number.

Here is an example with some made-up HTML that outlines how I think doing that could 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>

The desired output would of course be:

  1. ...
  2. Some text that I want to refer to later ...
  3. ...
  4. According to 2., ...

Is there something like this in real-life HTML?

Gerry answered 19/8, 2014 at 11:24 Comment(0)
C
1

HTML doesn't provide such mechanism. You need server-side or client-side scripting to achieve this.

You can also try using CSS counter properties: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Counters

Conk answered 19/8, 2014 at 12:3 Comment(0)
G
1

For what it's worth, I have accomplished what I wanted using jQuery. It doesn't answer the question directly, but can be useful to someone. It works for nested lists too.

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:

  1. ...
  2. Nested list
    1. ...
    2. Some text that I want to refer to later ...
    3. ...
    4. Another text that I want to refer to ...
    5. According to 2.4., ...
  3. According to 2.2., ...
Gerry answered 19/8, 2014 at 15:37 Comment(0)
A
-1

Try using

id="something"

and then modify that accordingly, but notice that CSS id's have to be unique.

Abb answered 19/8, 2014 at 11:50 Comment(1)
You seem to given up reading the question after the first sentence and thus answered something unrelated to the problem.Aggie

© 2022 - 2024 — McMap. All rights reserved.