Эмм... это одна строчка:
let list = document.querySelectorAll('li');
for( let li of list ){
li.dataset.liCount = li.querySelectorAll('li').length;
li.insertAdjacentHTML('afterbegin', 'Вложено li: ' + li.dataset.liCount); // для демо
}
<ul>
<li>
<ul>
<li></li>
<li></li>
<li>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
</ul>
</li>
<li></li>
</ul>
А в вашем коде, сложно сказать, где конкретно ошибка - местами есть косяки и он просто не работает (например, если в процессе найдется child-UL, то ему тоже запишется dataset). Попробовал написать рабочий вариант, максимально похожий на ваш)) Понадобилась внешняя переменная (т.к. функция вызывает сама себя), чтобы не запутавшись, спокойно плюсовать ему +1 после каждого найденного li. И в самом конце - записать это число в dataset.
let innerLi;
for (let li of document.getElementsByTagName('li')) {
innerLi = 0;
li.dataset.liCount = countChild(li);
li.insertAdjacentHTML('afterbegin', 'Вложено li: ' + li.dataset.liCount); // для демо
}
function countChild(li) {
if (!li.children.length) { return innerLi; }
// Детей будет ноль - функция сразу прервется
for (let child of li.children) {
if (child.tagName === "LI") {
innerLi++;
}
countChild(child);
}
return innerLi;
}
<ul>
<li>
<ul>
<li></li>
<li></li>
<li>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
</ul>
</li>
<li></li>
</ul>
Но работать с такими переменными будет не очень удобно, как только у вас код станет чуть длиннее. Поэтому есть более классный вариант (см. google - функции-конструкторы):
for (let li of document.getElementsByTagName('li')) {
li.dataset.liCount = ( new Count() ).child(li);
li.insertAdjacentHTML('afterbegin', 'Вложено li: ' + li.dataset.liCount); // для демо
}
function Count() {
// функция при вызове new - будет создавать объект. this будет ссылаться на этот объект
this.innerLi = 0;
this.child = function(li) {
if (!li.children.length) { return this.innerLi; }
for (let child of li.children) {
if (child.tagName === "LI") {
this.innerLi++;
}
this.child(child);
}
return this.innerLi;
}
}
<ul>
<li>
<ul>
<li></li>
<li></li>
<li>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
</ul>
</li>
<li></li>
</ul>