Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript nodeValue returns null

Title should make my problem well described.Here goes my code.

<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 the problem..?

like image 341
neonant Avatar asked Oct 20 '10 12:10

neonant


2 Answers

In order to get [merged] text content of an element node:

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

In order to get text content of a text node:

function vb(){
alert(document.getElementById("adiv").firstChild.firstChild.nodeValue);
}
like image 176
Sergey Ilinsky Avatar answered Oct 22 '22 19:10

Sergey Ilinsky


You are missing a firstChild:

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

(I know it sounds weird but this is how text nodes work)

like image 28
GôTô Avatar answered Oct 22 '22 21:10

GôTô