element.children 是只读属性,返回实时 htmlcollection,仅含直接子元素节点(如、),不含文本/注释节点;需用for循环或展开语法遍历,区别于包含所有节点的childnodes。

element.children 是 JavaScript 中用于获取指定元素的所有 HTML 子元素节点(Element 节点)的只读属性,返回一个 HTMLCollection 对象。它不包含文本节点、注释节点或空格,只返回标签元素(如 <div>、<code><p></p>、<span></span> 等)。
基本用法和返回值特点
调用方式简单直接:
const parent = document.getElementById('container');
const childElements = parent.children;
注意几个关键点:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 返回的是 实时的 HTMLCollection(不是数组),DOM 变化会自动反映在该集合中;
- 只包含直接子元素(不递归嵌套);
- 按 DOM 中的出现顺序排列,索引从 0 开始;
- 不能直接使用
map、forEach等数组方法(需转换)。
遍历 children 的常用方式
由于 children 是 HTMLCollection,推荐以下安全遍历方式:
-
for 循环(最兼容、推荐):
for (let i = 0; i -
转成数组后使用数组方法:
Array.from(element.children).forEach(child => child.style.color = 'red');
或使用展开语法:[...element.children].forEach(...) -
for...of 循环(现代浏览器支持):
for (const child of element.children) { child.classList.add('active'); }
children 与 childNodes 的区别
这是初学者容易混淆的地方:
-
element.children→ 只返回元素节点(nodeType === 1); -
element.childNodes→ 返回所有子节点,包括文本节点(换行、空格)、注释节点等(nodeType可能为 1/3/8)。
例如,HTML 中有换行和缩进时:<div id="box">\n <span>A</span>\n <p>B</p>\n</div>box.children.length === 2,但 box.childNodes.length 往往是 5 或更多(含文本节点)。
实际使用小提示
- 获取第一个/最后一个子元素:
element.children[0]或element.children[element.children.length - 1]; - 检查是否有子元素:
element.children.length > 0; - 想过滤特定标签?配合
Array.from()+filter():Array.from(el.children).filter(c => c.tagName === 'LI'); - 注意:IE9+ 支持
children,完全无需 polyfill。










