首页 > firstChild.nodeValue vs. innerHTML

firstChild.nodeValue vs. innerHTML

<span id="msg"></span>
document.getElementById('msg').firstChild.nodeValue = message;

firstChild.nodeValue为什么会出错?


善用搜索,楼主,建议去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里有多个节点的话,
这两货的区别大概就如:


没有子节点


firstChild定义和用法

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

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

【热门文章】
【热门文章】