← 中文资源

简体中文版本

firstChild 可能是空白文本节点

innerHTML 会把缩进换行变成文本节点,firstChild 拿到的可能是空白;要元素就用 firstElementChild 与 nextElementSibling,childNodes 与 children 的数量因此不同。

阅读英文原文

实现说明

顶层就这几处状态:host、first。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 每一步打印都带着自己的标签:childNodes:、children:。

常见问题

「firstChild 可能是空白文本节点」能在裸 Node.js 里跑吗?

不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

核心语句

const host = document.createElement('div');
const first = host.firstElementChild;
host.innerHTML = `
  <span>alpha</span>
  <span>beta</span>
`;

代码示例

// HTML formatting becomes text nodes: firstChild may not be the element you meant
const host = document.createElement('div');
host.innerHTML = `
  <span>alpha</span>
  <span>beta</span>
`;

console.log(host.firstChild.constructor.name);   // Text - the newline/indent node!
console.log(host.firstElementChild.textContent); // alpha - skips text nodes

// childNodes lists every node type; children lists elements only
console.log('childNodes:', host.childNodes.length); // 5 (text, span, text, span, text)
console.log('children:', host.children.length);     // 2

// Sibling navigation has the same split: nextSibling vs nextElementSibling
const first = host.firstElementChild;
console.log(first.nextElementSibling.textContent); // beta
console.log(first.nextSibling.nodeType);           // 3 (text node)