如何为每个列表项(LI)添加带括号的子项计数?跳过无内部列表项的LI
Solution: Add Subitem Counts to Parent List Items
First, let's fix the issues in your current code and build a scalable solution that automatically adds subitem counts to any list item (LI) containing child lists, skipping those that don't.
Issues in Your Current Code
document.getElementById('t1').childElementCountreturns a number (the count of child elements), not an array. Looping overcount.lengthdoesn't work because numbers don't have alengthproperty.- Your function is tied to specific IDs (
t1,t2,t3), which isn't flexible for larger or dynamic lists. - You're only showing alerts instead of updating the actual list item text with the count.
Working Solution
Here's a revised approach that will:
- Find all list items on the page
- Check if each list item has direct child
<ul>or<ol>elements - Count the total number of sub-items (child LIs) in those lists
- Append the count in parentheses to the parent LI's text
JavaScript Code
function addSubitemCounts() { // Grab all list items on the page const listItems = document.querySelectorAll('li'); listItems.forEach(li => { // Target only direct child unordered/ordered lists (ignore nested ones deeper down) const childLists = li.querySelectorAll(':scope > ul, :scope > ol'); if (childLists.length > 0) { let totalSubitems = 0; // Sum up all child LIs across direct child lists childLists.forEach(list => { totalSubitems += list.children.length; }); // Add the count to the LI's existing text (preserve original content) li.firstChild.textContent += ` (${totalSubitems})`; } }); } // Run the function automatically when the page finishes loading window.addEventListener('load', addSubitemCounts);
Updated HTML
You can remove the inline onclick handlers since we're running the function on page load:
<ul> <li>About Animals <ul> <li>Mammals <ul> <li>Cows</li> <li>Donkeys</li> <li>Dogs</li> <li>Tigers</li> </ul> </li> <li>Others <ul> <li>Snakes</li> <li>...</li> </ul> </li> </ul> </li> </ul>
How It Works
querySelectorAll('li')captures every LI element on the page.:scope > ul, :scope > olensures we only look at lists directly nested under the current LI (not lists inside sub-items).- We calculate the total number of sub-items by summing the children of each direct child list.
li.firstChild.textContent += ...appends the count to the LI's text without disrupting the nested lists.
Final Result
After running the function, your list will display like this:
- About Animals (2)
- Mammals (4)
- Cows
- Donkeys
- Dogs
- Tigers
- Others (2)
- Snakes
- ...
- Mammals (4)
内容的提问来源于stack exchange,提问作者newbie
相关产品推荐
相关产品推荐

