10

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

neonant
  • 832
  • 3
  • 16
  • 25

3 Answers3

18

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);
}
Sergey Ilinsky
  • 31,255
  • 9
  • 54
  • 56
  • 1
    Thanks..actually double firstchild is kinda weird. – neonant Oct 20 '10 at 13:35
  • it's not weird... firstChild is and the firstChild of is the textnode itself. – Stumpy7 Mar 20 '13 at 10:48
  • the text inside the node IS the text node. For instance, for a formatted document like `\nbaz\n` the childNodes property of the `foo` node returns `NodeList [ #text "\n", , #test "\n" ]` – solstice333 Aug 07 '17 at 02:48
13

You are missing a firstChild:

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

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

GôTô
  • 7,974
  • 3
  • 32
  • 43
-2

<text> node is not supported in IE 7.

dur
  • 15,689
  • 25
  • 79
  • 125
unigg
  • 466
  • 3
  • 8