2010-10-20 18 views
8

Il titolo dovrebbe descrivere bene il mio problema. Qui va il mio codice.Javascript nodeValue restituisce 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"/> 

dove si trova il problema ..?

risposta

14

Al fine di ottenere [unito] il contenuto del testo di un nodo elemento:

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

al fine di ottenere il contenuto del testo di un nodo di testo:

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

Grazie..attualmente il doppio firstchild è un po 'strano. –

+0

non è strano ... firstChild è e il primo bambino di è il textnode stesso. – Stumpy7

+0

textContent funziona meglio per me: D Grazie! :) –

10

ti manca un firstChild:

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

(lo so che suona strano, ma questo è come funzionano i nodi di testo)

+3

Sì, molto strano, ma grazie! ;) – musefan

+0

Non funziona in IE 9,8 – Alex

+0

@ user1473206 hai un jsfiddle o simile per testarlo? –

-2

<text> nodo non supportato in IE 7.