使用 children 属性获取 htmlcollection,或使用 queryselectorall() 配合 css 选择器获取 nodelist。前者仅包含元素节点且实时响应 dom 变化,后者支持复杂筛选但返回静态快照。

children 与 childNodes 的区别是什么
children 只包含元素节点(Node.ELEMENT_NODE),自动过滤掉文本和注释节点;而 childNodes 包含所有类型的子节点。在需要精确遍历 DOM 结构时,应优先使用 children 以避免处理空白文本节点带来的干扰。

<div id="parent">
<span>A</span>
<!-- comment -->
Text Node
<b>B</b>
</div>
<script>
const parent = document.getElementById('parent');
console.log(parent.childNodes.length); // 5: span, text, comment, text, b
console.log(parent.children.length); // 2: span, b
for (let i = 0; i < parent.children.length; i++) {
console.log(parent.children[i].tagName);
}
</script>
上述代码中,childNodes 长度为 5,因为包含了两个文本节点和一个注释节点;而 children 长度为 2,仅包含 和 两个元素。循环遍历 children 可安全获取标签名,无需判断节点类型。
querySelectorAll() 如何筛选特定子元素
querySelectorAll() 接受 CSS 选择器字符串,返回当前匹配的所有元素的静态 NodeList。它比手动遍历 children 更灵活,支持类名、属性、伪类等复杂条件,适合需要批量操作或查找深层嵌套子元素场景。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。

- One
- Two
- Three
通过 .item.active 选择器,querySelectorAll() 精准定位到同时具有 item 和 active 类的 元素。若需获取所有列表项,可使用通用选择器 li。该方法返回的 NodeList 不支持直接修改 DOM,但可迭代进行样式或数据操作。
动态添加子元素后 children 集合会更新吗
会。由于 children 是 HTMLCollection,它是实时的(live),任何对 DOM 结构的修改都会立即反映在该集合的长度和内容上。相比之下,querySelectorAll() 返回的 NodeList 是静态的(static),不会随 DOM 变化而自动更新。
<div id="container"></div>
<script>
const container = document.getElementById('container');
console.log(container.children.length); // 0
const div = document.createElement('div');
div.textContent = 'New';
container.appendChild(div);
console.log(container.children.length); // 1
console.log(container.children[0].textContent); // "New"
// 对比 querySelectorAll
const initialNodes = container.querySelectorAll('div');
console.log(initialNodes.length); // 0 (静态快照)
const anotherDiv = document.createElement('div');
anotherDiv.textContent = 'Another';
container.appendChild(anotherDiv);
console.log(initialNodes.length); // 仍为 0,未更新
console.log(container.querySelectorAll('div').length); // 2,重新查询才更新
</script>
在动态构建 UI 时,若依赖 children 进行后续逻辑判断,其实时性优势明显。但若需缓存某时刻的子元素列表用于批量处理,应使用 querySelectorAll() 并明确其静态特性,避免意外行为。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










