Add the number of descendants for each li node
I think functional coding style is best suited here, because it will significantly reduce amount of code. Also, you will have clearly separated structure consisting of functions with single responsibility.

Suggested solution

function insertCounts(root) {
    forEachElement(root, (el) =&gt; el.innerHTML = countText(count(el)) + el.innerHTML, el =&gt; !isLeaf(el) &amp;&amp; (el.tagName === 'LI'));
}

function countText(count) {
     return `[${count}]`;
}

function forEachElement(root, apply, predicate = () =&gt; true) {
    Array.from(root.children).forEach(el =&gt; { predicate(el) &amp;&amp; apply(el); forEachElement(el, apply, predicate) });
}

function count(root) {
    return Array.from(root.children).reduce((acc, el) =&gt; isLeaf(el) ? acc + 1 : acc + count(el), 0);
}

function isLeaf(elem) {
    return (elem.firstElementChild === null);
}


try {
    if(document.body.firstElementChild !== null) {
        insertCounts(document.body.firstElementChild);
    }
}  catch (err) {
    console.log(err);
}