You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为每个列表项(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').childElementCount returns a number (the count of child elements), not an array. Looping over count.length doesn't work because numbers don't have a length property.
  • 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:

  1. Find all list items on the page
  2. Check if each list item has direct child <ul> or <ol> elements
  3. Count the total number of sub-items (child LIs) in those lists
  4. 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 > ol ensures 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
      • ...

内容的提问来源于stack exchange,提问作者newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:09:57