HTML中childNodes和children有什么区别
文章类型:html
发布者:hp
发布时间:2026-05-03
在 HTML DOM 操作中,childNodes 和 children 都是用于获取元素子内容的属性
childNodes 是 DOM 规范中的标准属性,它返回指定节点下的所有直接子节点。
<div>, <p>),还包含:<!-- 注释 -->。<div id="box">
<p>Hello</p>
</div>
//document.getElementById('box').childNodes.length 的结果通常是 3判断节点类型:由于包含非元素节点,遍历时通常需要使用 nodeType 进行判断:
nodeType === 1:元素节点nodeType === 3:文本节点nodeType === 8:注释节点children 属性更加“干净”,它只返回指定元素下的子元素节点(Element Nodes)。
document.getElementById('box').children.length 的结果是 1,即那个 <p> 元素。children 只返回元素节点。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>
childNodes。
暂无评论,快来发表第一条评论吧~