如何在javascript中使用html DOM的节点关系访问html元素

How to access html element using node relationship of html DOM in javascript

本文关键字:html DOM 节点 关系 元素 访问 javascript      更新时间:2023-09-26

我想通过节点关系访问html元素,如parentNode,fastChild,nextSibling等。但我下面的代码不能正常工作。我的代码看起来像:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>
    <body>
        <p>This is first para</p>
        <div id="mydiv">
            <h2 align="center">This is the Header</h1>
            <p align="justify">This is the Paragraph</p>
            <marquee scrolldelay="10">This is maquee</marquee>
        </div>
        <p>This is last para</p>
        <script type="text/javascript">
            var mydiv = document.getElementById("mydiv");
            alert(mydiv.parentNode + "'n" +
                  mydiv.firstChild + "'n" +
                  mydiv.childNodes[1] + "'n" +
                  mydiv.lastChild + "'n" +
                  mydiv.previousSibling + "'n" +
                  mydiv.nextSibling);
        </script>
    </body>
</html>

警告框输出如下:

[object HTMLBodyElement]
[object Text]
[object HTMLHeadingElement]
[object Text]
[object Text]
[object Text]

但是对于div, parentNode,fastChild,childNodes[1],lastChild,previousSibling和nextSibling应该是body,h2,p,marquee,p和p.那么为什么输出看起来像上面?

将各种元素前后的空白转换为文本节点。你可以看到你想要的结果,如果你删除所有空格:

<p>This is first para</p><div id="mydiv"><h2 align="center">This is the Header</h1><p align="justify">This is the Paragraph</p><marquee scrolldelay="10">This is maquee</marquee></div><p>This is last para</p>

示例:http://codepen.io/paulroub/pen/hpIow

MDN Node.firstChild文档对此有更详细的解释。

请注意,等效的jQuery方法将忽略文本节点,并为您提供您想要的子节点,下一个节点等。

您还可以循环遍历子节点,跳过文本节点,直到找到其他节点:

for ( var i = 0; i < mydiv.childNodes.length; ++i )
{
  if (mydiv.childNodes[i].nodeType != Node.TEXT_NODE)
  {
    firstNon = mydiv.childNodes[i];
    break;
  }
}

示例:http://codepen.io/paulroub/pen/chLCo

你可以使用firstElementChild来绕过空白(或者只是使用现有的js库,如果你所做的不是仅仅为了学习的目的,处理DOM自己不是一个非常愉快的经验)