Javascript nodeValue returns null

17,608

Solution 1

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);
}

Solution 2

You are missing a firstChild:

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

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

Share:
17,608
neonant
Author by

neonant

Updated on June 14, 2022

Comments

  • neonant
    neonant about 2 years

    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
    neonant over 13 years
    Thanks..actually double firstchild is kinda weird.
  • Stumpy7
    Stumpy7 over 11 years
    it's not weird... firstChild is <Text> and the firstChild of <Text> is the textnode itself.
  • GôTô
    GôTô over 9 years
    @user1473206 do you have a jsfiddle or similar to test this?
  • Alex
    Alex over 9 years
    I have tried this on ie8 and 9, nodeValue returned as Null
  • solstice333
    solstice333 almost 7 years
    the text inside the node IS the text node. For instance, for a formatted document like <foo>\n<bar>baz</bar>\n</foo> the childNodes property of the foo node returns NodeList [ #text "\n", <bar>, #test "\n" ]