最直接准确的方式是用 ol.children.length,它只统计 ol 的直接子 li 元素,自动过滤非元素节点,性能好且语义清晰;需注意空值检查和 DOM 加载时机。

用 document.querySelectorAll 获取 ol 下的 li 数量
最直接的方式是选中所有 ol 元素,再对每个 ol 统计其子 li 个数。注意:querySelectorAll('ol li') 会匹配所有嵌套层级的 li(包括子 ol 里的),如果只想要**直接子项**,必须用 > 限定:
const ol = document.querySelector('ol');
const count = ol ? ol.querySelectorAll('li').length : 0;
但这个写法仍包含嵌套 li。要严格只算第一层,改用:
const count = ol ? ol.querySelectorAll('> li').length : 0;
用 children 属性更轻量、更准确
children 只返回元素节点(li),自动过滤文本节点和注释,且天然只含直接子元素,比 querySelectorAll 性能略好、语义更清晰:
- 如果页面只有一个
ol:const count = document.querySelector('ol')?.children.length || 0; - 如果有多个
ol,需遍历:document.querySelectorAll('ol').forEach(ol => { console.log(ol.children.length); }); - 注意:
children是HTMLCollection,不是数组,不能直接用map或filter,要用Array.from(ol.children)转换
为什么不用 getElementsByTagName?
ol.getElementsByTagName('li') 看似简单,但它会递归查找所有后代 li,和 querySelectorAll('ol li') 行为一致,无法限制层级。除非你明确需要全部嵌套项,否则容易误算。
另外,它返回的是动态 HTMLCollection,若后续 DOM 变化,长度可能意外改变;而 children 和 querySelectorAll 返回静态集合,更可控。
兼容性与边界情况
现代浏览器都支持 children 和 querySelectorAll,IE9+ 没问题。但要注意几个易错点:
-
document.querySelector('ol')返回null时,直接链式调用.children.length会报Cannot read property 'length' of null—— 必须加空值检查(?.可选链或if (ol)) -
ol标签里混有非li元素(比如div或注释),children会跳过它们,只计li;而childNodes会把空白文本节点也算进去,千万别用 - 如果
ol是通过 JS 动态插入的,确保脚本在 DOM 加载完成后执行(比如放在
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











