children属性返回仅包含html元素节点的实时htmlcollection,不包括文本或注释节点;可索引访问、for...of遍历,需转数组才能用foreach/map等方法。

JavaScript 中通过 children 属性可以获取元素的**子元素节点集合(仅 HTML 元素节点)**,它返回一个 HTMLCollection,只包含标签元素(如 <div>、<code><p></p>),不包括文本节点、注释节点等。
children 和 childNodes 的区别
children 是“纯元素”的子集,而 childNodes 返回所有类型的子节点(包括空白文本节点)。在实际开发中,如果只想操作子标签,children 更安全、更直观。
-
element.children→ 只返回子 元素节点(HTML 标签) -
element.childNodes→ 返回所有子节点(元素、文本、注释等)
如何使用 children 获取和遍历子元素
直接访问 children 属性即可,它是一个只读的 HTMLCollection,支持索引访问、length 和 for...of 遍历(现代浏览器):
- 获取第一个子元素:
parent.children[0] - 获取子元素个数:
parent.children.length - 遍历所有子元素(推荐用
for...of):for (const child of parent.children) { console.log(child); } - 转为数组以便使用
map、filter等方法:Array.from(parent.children)或[...parent.children]
注意兼容性和常见陷阱
children 在所有现代浏览器和 IE9+ 中都支持,但需注意以下几点:
- 返回的是 实时集合(live collection):如果动态增删子元素,
children内容会自动更新 - 不能直接用
forEach(HTMLCollection没有该方法),需先转数组 - 空格、换行在 HTML 中会被解析为文本节点,但
children会自动忽略它们——这是它的优势
简单示例
假设 HTML 如下:
<div id="container"> <br> <h2>标题</h2> <br> <p>段落</p> <br> </div>
JS 获取子元素:
const container = document.getElementById('container');<br>console.log(container.children.length); // 输出 2<br>console.log(container.children[0].tagName); // "H2"











