简体   繁体   中英

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

That's what nodeValue does according to the specification , it returns this

Comment               - content of the comment
Document              - null
DocumentFragment      - null
DocumentType          - null
Element               - null
NamedNodeMap          - null
EntityReference       - null
Notation              - null
ProcessingInstruction - entire content excluding the target
Text                  - content of the text node

Note that it returns null for anything but comments, textNodes and processing instruction, for all other node types null is explicitly returned.

To get the text content of an Element node, use textContent ( innerText for older IE), to get the HTML of an Element node, use innerHTML

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM