text节点nodeType为3,comment节点为8,最可靠区分方式是检查nodeType属性;nodeValue和textContent可读取内容但不能替代类型判断,且不可依赖字符串特征如"--"识别。

在 DOM 中,text 节点(Text Node)和comment 节点(Comment Node)是两种不同类型的节点,它们的 nodeType 值不同,可通过属性或方法明确区分——无需依赖内容猜测。
看 nodeType 属性是最直接的方式
每个节点都有 nodeType 属性,用于标识其类型:
- text 节点的
nodeType === 3</li><li>comment 节点的 <code>nodeType === 8</li></ul><p>例如:</p><font size="2"><pre class="brush:php;toolbar:false;"> const el = document.getElementById('container'); el.childNodes.forEach(node => { if (node.nodeType === 3) { console.log('这是文本节点:', node.textContent.trim()); } else if (node.nodeType === 8) { console.log('这是注释节点:', node.textContent); } });用 nodeValue 或 textContent 判断内容但不替代 nodeType
nodeValue 对两者都有效,而 <code>textContent在 comment 节点上也返回注释内容(但会忽略其中的 HTML 标签):- text 节点:
nodeValue和textContent都返回纯文本内容(含空格、换行) - comment 节点:
nodeValue返回注释内“”之间的原始字符串;textContent行为一致,但注意它不会解析 HTML
⚠️ 注意:不能单靠
nodeValue是否含"--"或"<!--"来判断,因为 text 节点本身也可能包含这些字符(比如用户输入了<!-- 这是普通文字 -->)。遍历子节点时避开注释节点(常见需求)
若只想处理真实文本内容,可过滤掉 comment 节点:
Array.from(el.childNodes) .filter(node => node.nodeType === 3 && node.textContent.trim()) .forEach(textNode => { console.log('有效文本:', textNode.textContent.trim()); });或者更通用的做法是跳过所有非元素/非文本节点:
-
nodeType === 1:元素节点(如 div、span) -
nodeType === 3:文本节点(关注对象) -
node.nodeType === 8:注释节点(通常跳过)
动态创建时主动指定节点类型
用 JS 创建时,类型由方法决定:
-
document.createTextNode("hello")→ text 节点 -
document.createComment("说明信息")→ comment 节点
插入后它们在 DOM 中保持各自类型,可通过上述方式持续识别。
- text 节点:

















