To achieve this, utilize CSS counters. By applying a :before pseudo-element to the li element, you can display the count.
Set the counter reset on the ol element so that the count resets with each new instance of an ordered list. This eliminates the need to manually track the number of lists or the items within each list. Additionally, you can configure the counter to include nested lists within the li items, displaying them as 1.1, 1.2, and so forth.
You have the flexibility to restart the count for each individual order list and customize counts and displays for different lists. This gives you full control over the structure.More on using CSS counters here
UPDATE: Following @Bhuwan Bhatt's suggestion, a JavaScript-only approach has been added for setting the counter via querySelectorAll. It first selects all ols in the document and then retrieves the number of lis within each ol. The counter is then set to the length of lis (+1 due to zero indexing).
var lists = document.querySelectorAll('ol');
var listsLength = lists.length;
for (i=0; i<listsLength; i++) {
var lis = lists[i].querySelectorAll('li');
var lisLength = lis.length + 1;
lists[i].style.counterReset = 'section ' + lisLength;
}
ol {
list-style: none;
padding-left: 0;
counter-reset: section ; /* Creates a new instance of the
section counter with each ul
element - count set to 4
because of zero indexing of the list */
}
li::before {
counter-increment: section -1; /* Using a negative number
to decrement the count */
content: counter(section); /* Display the count as :before element */
margin-right: 15px; /* provide a margin between the count and the li */
}
<ol>
<li>test 1</li>
<li>test 2</li>
<li>test 3</li>
</ol>
<ol>
<li>test 1</li>
<li>test 2</li>
<li>test 3</li>
<li>test 3</li>
</ol>
<ol>
<li>test 1</li>
<li>test 2</li>
</ol>