0

我对 JavaScript 中文本节点的属性有点困惑。假设我有这段 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>

onload()功能:

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

这个http://www.w3schools.com/js/js_htmldom_navigation.asp告诉: “文本节点的 nodeValue 是文本本身”,但我得到这个输出:

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

你能解释一下为什么nodeValuereturn nullforelement node和“nothing” fortext node吗?

编辑: 这里很好地描述了有关空白的内容: https ://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Whitespace_in_the_DOM

4

2 回答 2

3

这就是nodeValue根据规范所做的,它返回这个

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

请注意,除了注释、textNodes 和处理指令之外null的任何内容都会返回,因为所有其他节点类型都是显式返回的。null

要获取 Element 节点的文本内容,请使用textContentinnerText对于较旧的 IE),要获取 Element 节点的 HTML,请使用innerHTML

于 2015-03-24T22:17:17.780 回答
2

为什么 nodeValue 返回null元素节点

因为元素节点没有值。他们基本上只有一个名字、属性和孩子。

……文本节点“什么都没有”?

它确实返回了一些东西:这些元素节点之间的空白。

于 2015-03-24T22:17:31.287 回答