HTML中childNodes和children有什么区别

文章类型:html

发布者:hp

发布时间:2026-05-03

一:引言

在 HTML DOM 操作中,childNodes 和 children 都是用于获取元素子内容的属性

二:区别

1:childNodes:返回所有子节点

childNodes 是 DOM 规范中的标准属性,它返回指定节点下的‌所有‌直接子节点。

  • 节点类型多样‌:它不仅包含我们常见的 HTML 元素(如 <div>, <p>),还包含:
  • 文本节点 (Text)‌:元素之间的空格、换行符、纯文本内容。
  • 注释节点 (Comment)‌:HTML 中的 <!-- 注释 -->
  • 其他节点‌:如处理指令等(较少见)。
<div id="box">
    <p>Hello</p>
</div>
//document.getElementById('box').childNodes.length 的结果通常是 ‌3‌

判断节点类型‌:由于包含非元素节点,遍历时通常需要使用 nodeType 进行判断:

  • nodeType === 1:元素节点
  • nodeType === 3:文本节点
  • nodeType === 8:注释节点

2:children:仅返回子元素

children 属性更加“干净”,它只返回指定元素下的‌子元素节点‌(Element Nodes)。

  • 自动过滤‌:它会自动忽略所有的文本节点(包括空白字符)和注释节点。
  • 结果更直观‌:

document.getElementById('box').children.length 的结果是 ‌1‌,即那个 <p> 元素。
  • 兼容性注意‌:
  • 在现代浏览器及 IE9+ 中,children 只返回元素节点。
  • 在极旧的 IE 版本(IE6-8)中,children 可能会包含注释节点,但在现代前端开发中通常无需考虑此兼容性问题

三:代码

<div id="parent">
    <!-- 这是一个注释 -->
    <span>Item 1</span>
    <span>Item 2</span>
</div>
const parent = document.getElementById('parent');

// 1. 使用 childNodes
console.log(parent.childNodes.length); 
// 输出可能为 5 或更多(取决于换行和空格):
// [文本节点(换行), 注释节点, 文本节点(换行), span元素, 文本节点(换行), span元素, 文本节点(换行)]

// 遍历 childNodes 获取第一个元素节点需要额外判断
for (let i = 0; i < parent.childNodes.length; i++) {
    if (parent.childNodes[i].nodeType === 1) {
        console.log("找到第一个元素:", parent.childNodes[i]);
        break;
    }
}

// 2. 使用 children
console.log(parent.children.length); 
// 输出为 2:[span, span]

// 直接获取第一个子元素,无需判断
console.log("第一个子元素:", parent.children); // <span>Item 1</span>

四:建议

  1. 只关心 HTML 标签(元素节点),不关心空格或注释。使用 children 代码更简洁,性能略好,且不需要额外的类型判断逻辑。
  2. ‌需要读取或修改元素内的纯文本内容,且这些文本没有被包裹在标签内时。需要处理或移除 HTML 注释节点时。在进行底层的 DOM 库开发或框架源码研究时使用childNodes
  3. 只需要获取子元素的数量,可以使用 element.childElementCount,它等同于 element.children.length,需要将 children 或 childNodes 转换为数组以使用 map、filter 等现代数组方法,可以使用 Array.from(element.children) 或 [...element.children]。
评论
0条评论遵守法律,文明用语,共同建设文明评论区

暂无评论,快来发表第一条评论吧~