2010-10-20 83 views
8

标题应该使我的问题得到很好的描述。下面是我的代码。Javascript nodeValue返回null

<div id="adiv"><text>Some text</text></div>  
<script type="text/javascript"> 
function vb(){ 
alert(document.getElementById("adiv").firstChild.nodeValue); //returns null 
} 
</script> 
<input type="button" onclick="vb();" value="get"/> 

wheres问题..?

回答

14

为了得到一个元素节点的[合并]文本内容:

function vb(){ 
var textnode = document.getElementById("adiv").firstChild; 
alert(textnode.textContent || textnode.innerText); 
} 

为了得到文本节点的文本内容:

function vb(){ 
alert(document.getElementById("adiv").firstChild.firstChild.nodeValue); 
} 
+1

谢谢..实际上,doubleChild有点奇怪。 – 2010-10-20 13:35:11

+0

这不是奇怪的... firstChild是的firstChild是textnode本身。 – Stumpy7 2013-03-20 10:48:44

+0

textContent最适合我:D谢谢! :) – 2016-03-18 09:49:43

10

你缺少一个则firstChild:

alert(document.getElementById("adiv").firstChild.firstChild.nodeValue); 

(我知道这听起来有些不可思议,但这是文本节点是如何工作的)

+3

是的很奇怪,但谢谢! ;) – musefan 2011-12-06 15:07:28

+0

无法在IE浏览器9,8 – Alex 2015-01-28 10:11:43

+0

@ user1473206你有一个jsfiddle或类似的测试呢? – 2015-01-28 10:28:54

-2

<text>节点在IE 7中不受支持。