javascripthtmltextnodenodevalue

JavaScript text nodes properties


I'm little confused about properties of text nodes in JavaScript. Let say that I have this piece of html:

<html lang="en-US">
<head>
    <title>JavaScript test</title>
    <script type="text/javascript" src="test.js"></script>
</head>
<body onload="load()">
    <div>
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
    </div>
    <ul>
        <li>1.</li>
        <li>2.</li>
    </ul>
</body>

And onload() function:

function load()
{
    var bodyChildren = document.childNodes[0].childNodes;
    for(var i = 0; i < bodyChildren.length; i++) 
    {
        alert(bodyChildren[i].nodeType
            + ": " + bodyChildren[i].nodeName
            + ": " + bodyChildren[i].nodeValue);
    }
}

This http://www.w3schools.com/js/js_htmldom_navigation.asp tells: "nodeValue for text nodes is the text itself", but I'm getting this output:

3: #text: 
1: DIV: null
3: #text: 
1: UL: null
3: #text: 

Can you explain me why nodeValue returns null for element node and "nothing" for text node?

Edit: The stuff about white spaces is nicely described here: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Whitespace_in_the_DOM


Solution

  • why nodeValue returns null for element node

    Because element nodes don't have values. They basically only have a name, attributes and children.

    …and "nothing" for text node?

    It does return you something: the whitespace between those element nodes.