2010-10-20 90 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中不受支持。