2

在以下脚本中,我尝试在DOM 树中移动,但没有得到预期的输出。

这里面只有一小段html

<p id="para">This is inside the <em>p</em> tag.</p>

当我穿过树时,这就是我得到的:

Node Name : P
Node Type : 1
Node Value : null


Node Name : HTML
Node Type : 1
Node Value : null

<html>
<head>
    <title>JavaScript</title>
</head>

<body> 
    <p id="para">This is inside the <em>p</em> tag.</p>

    <script type="text/javascript">
        function nodeStatus(node) {
            document.write("Node Name : " + node.nodeName + "<br />");
            document.write("Node Type : " + node.nodeType + "<br / >");
            document.write("Node Value : " + node.nodeValue + "<br / >");
            document.write("<br / > <br / >");
        }
        var curElement = document.getElementById("para");
        nodeStatus(curElement); // p tag
        curElement = document.firstChild; // This is inside the 
        nodeStatus(curElement);
        curElement = document.nextSibling; // em tag
        nodeStatus(curElement);
        curElement = document.firstChild; // p
        nodeStatus(curElement); 
    </script>
</body>

为什么我不能从text-node?

我作为节点名称获得的HTML是什么?我没有将任何节点命名为HTML

jsFiddle:http: //jsfiddle.net/HmkJQ/

4

2 回答 2

5

您正在做的是从每一行代码中的顶级文档开始。你开始:

var curElement = document.getElementById("para");

你得到了预期的 p 元素。但是随后您尝试获取 p 元素的子元素,但是使用此代码

curElement = document.firstChild;

你得到的是文档本身的第一个孩子(这意味着根 html 元素!)。

相反,您应该按如下方式导航:

curElement = curElement.firstChild;

试试看。

于 2013-02-27T09:40:33.537 回答
0

NodeName 的节点HTML<html>元素,即document.firstChild。您没有得到任何文本节点,因为您正在遍历 HTML 元素,即 DOM 元素节点。在 MDN 上有更多关于此的内容

您的代码本身处理一个名为 的变量curElement,这表明您希望这些是元素节点,而不是它们的内容。

要获取位于元素节点内的节点,您可能需要获取childNodes任何给定的curElement.

于 2013-02-27T09:41:00.403 回答