'Numbering a nested list in a single ol list

I have an ordered list with some li tags in it. I want the The li tags with .sub-item class to be nested li tags. Is there a way I can reset numbering for the li tags having class? The list is as below:

<ol>
  <li>One</li>
  <li>Two</li>
  <li>THree</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Four</li>
</ol>

Currently I get which makes sense:

  1 One
  2 Two
  3 Three
  4 Sub Three 1
  5 Sub three 2
  6 Four

However using the class 'sub-item' I want this desired behaviour

  1 One
  2 Two
  3. Three
     a Sub three 1
     b Sub Three 2
  4 Four

I can not change the html part of the code, only can write css. Adding nested ol tags will not work in this case as I can not modify the html.



Solution 1:[1]

This will work.

.sub-item {
    list-style-type: lower-alpha;
}
<ol>
    <li>One</li>
    <li>Two</li>
    <li>THree
        <ol>
            <li class="sub-item">Sub three 1</li>
            <li class="sub-item">Sub three 2</li>
        </ol>
    </li>
    <li>Four</li>
</ol>

Solution 2:[2]

You can nest lists inside other lists, you can mix ordered and unordered list through nesting. Use start attribute to change the starting number.

    <ol>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
        <ol start='5'>
          <li>Five</li>
          <li>Six</li>
          <li>Seven</li>
        </ol>
      <li>Four</li>
    </ol>

Solution 3:[3]

Since you can't modify the HTML markup, the simplest solution is to use Javascript to correct it:

window.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll("li.sub-item:not(.sub-item ~ .sub-item)").forEach(el => {
    const parentItem = el.previousElementSibling;
    if (!parentItem) {
      return;
    }

    const items = [];
    for (let li = el; li && li.classList.contains("sub-item"); li = li.nextElementSibling) {
      items.push(li);
    }

    const ol = document.createElement("ol");
    ol.setAttribute("type", "a");
    items.forEach(li => ol.appendChild(li));
    parentItem.appendChild(ol);
  });
});
<ol>
  <li>One</li>
  <li>Two</li>
  <li>THree</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Four</li>
</ol>

(The .sub-item:not(.sub-item ~ .sub-item) syntax came from this answer.)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nitheesh
Solution 2 Alston Chan
Solution 3 Richard Deeming