zoukankan      html  css  js  c++  java
  • Dom之文档结构与遍历

    1、Document对象、它的Element对象和文档中表示文本的Text对象、comment对象都是Node对象。Node定义了以下重要的属性

      parentNode、childNodes、firstChild、lastChild、nextSibling、previousSibling、NodeType、NodeValue、NodeName(元素的标签名)

      其中:

        NodeType(节点类型)

          1 → 代表Element节点

          3 → 代表Text节点

          4 → 代表CDATASection节点

          8 → 代表Comment(注释)节点

          9 → 代表Document节点

          11 → 代表DocumentFragment节点

    2、当将主要的兴趣集中在文档的元素上而非它们之间的文本(和他们之间的空间)上时,有另一个API

      API第一部份:children属性

      API第二部份:Element(统称,其中包括firstElementChild、lastElementChild、nextElementSibling、previousElementSibling、childElementCount)属性

    Demo如下

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    <div id="wrapper">
        <div class="test" id="first">
            <span>First text</span>
        </div>
        <!-- here is the comment-->
        <div class="test" id="second">Second text</div>
        <div class="test" id="third">Third text</div>
        <div class="test" id="four">Four text</div>
        <div class="test" id="five">Five text</div>
        <div class="test" id="six">Six text</div>
    </div>
    </body>
    <script>
        var $ = function (id) {
            return document.getElementById(id);
        };
    
        var e = $("wrapper");
    
        /**
         * children与Element(firstElementChild等的统称)将主要关注的
         * 点集中在元素上,而不是文本上(例如text、comment)
         */
        (function () {
            console.log(e.children);
    
            console.log(e.firstElementChild);
            console.log(e.lastElementChild);
            console.log(e.firstElementChild.nextElementSibling);
            console.log(e.lastElementChild.previousElementSibling);
    
            console.log(e.childElementCount);//子元素的数量,返回的值和children.length相等
        })();
    
        /**
         * Document对象、它的Element对象和文档中表示文本的Text对象都是Node对象
         *
         */
        (function () {
            console.log(e.parentNode);// return body的node对象
            console.log(e.childNodes);// 返回该节点的子节点的实时表示,包含text、comment
            console.log(e.firstChild);// 该节点的子节点的第一个,没有则为null
            console.log(e.lastChild);// 该节点的子节点的最后一个,没有则为null
    
            var eFirst = $("first");
            console.log(eFirst.nextSibling);// 返回该节点的兄弟节点的下一个节点
            console.log(eFirst.nextSibling.nextSibling);// 这里返回注释节点
            console.log(eFirst.previousSibling);// 返回该节点的兄弟节点的上一个节点
    
        })();
    </script>
    </html>

    返回结果如下:

      

  • 相关阅读:
    JS中怎样获取当前日期的前一个月和后一个月的日期字符串
    JS中怎样将时间字符串转换成Date并比较大小
    Java中判断两个Date时间段是否有交集的方法
    gRPC中Java和node进行异构通信-互为客户端和服务端
    ffmpeg external libraries 下载地址
    libsvtav1 的 qp 和比特率对照表
    libsvtav1 AV1 编码速度比 libaom 大大提升
    ffmpeg windows 最新编译内部版本下载地址变更
    解开获取 aria2c 帮助信息的误区
    frei0r 过了好几年增加 aech0r 滤镜
  • 原文地址:https://www.cnblogs.com/qiuleo/p/4595684.html
Copyright © 2011-2022 走看看