firstChild.nodeValue vs. innerHTML



 <span id="msg"></span>


 document.getElementById('msg').firstChild.nodeValue = message;

firstChild.nodeValue 为什么会出错?

HTML JavaScript

好名都让狗起了 9 years, 9 months ago

没有子节点

被监禁的千雨 answered 9 years, 9 months ago

firstChild定义和用法

firstChild 属性返回被选节点的第一个子节点。
如果选定的节点没有子节点,则该属性返回 NULL。

因为你的 <span></span> 再没有子节点了,所以 .firstChild 的值已经是 null 了。
参考 http://www.w3school.com.cn/xmldom/prop_element_firstchild.asp

春哥胯下巨物 answered 9 years, 9 months ago

善用搜索,楼主,建议去 MDN 里找解释~.

firstChild from MDN

Returns the node's first child in the tree, or null if the node is childless. If the node is a Document, it returns the first node in the list of its direct children.

你的span确实没有子节点,哪怕给个文本节点如 空格\回车 ,都不会返回 null .

你提到 innerHTML 这里小提一下,如果说你的span里有多个节点的话,
这两货的区别大概就如:

gshase answered 9 years, 9 months ago

Your Answer