zoukankan      html  css  js  c++  java
  • JavaScript中Element与Node的区别,children与childNodes的区别【转】

    关于Element跟Node的区别,cilldren跟childNodes的区别很多朋友弄不清楚,本文试图让大家明白这几个概念之间的区别。

      Node(节点)是DOM层次结构中的任何类型的对象的通用名称,Node有很多类型,如元素节点,属性节点,文本节点,注释节点等,通过NodeType区分,常见的有:

    节点类型 NodeType
    元素element 1
    属性attr 2
    文本text 3
    注释comments 8
    文档document 9

      更多节点类型参考:https://developer.mozilla.org/en-US/docs/DOM/Node.nodeType?redirectlocale=en-US&redirectslug=nodeType

      Element继承了Node类,也就是说Element是Node多种类型中的一种,即当NodeType为1时Node即为ElementNode,另外Element扩展了Node,Element拥有id、class、children等属性。

      以上就是Element跟Node的区别。

      那么用document.getElementById("xxx")取到的是Node还是Element呢?我们来测试一下:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Demo</title>
    </head>
    <body>
        <div id="test">
            <p>One</p>
            <P>Two</p>
        </div>
        <script>
            var oDiv=document.getElementById("test");
            console.log(oDiv instanceof Node);        //true
            console.log(oDiv instanceof Element);    //true
        </script>
    </body>
    </html>
    

    我们可以看到用document.getElementById("xxx")取到的既是Element也是Node

    children是Element的属性,childNodes是Node的属性,我们再来测试一下:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Demo</title>
    </head>
    <body>
        <div id="test">
            <p>One</p>
            <P>Two</p>
        </div>
        <script>
            var oDiv=document.getElementById("test");
            console.log(oDiv.children[0] instanceof Node);        //true
            console.log(oDiv.children[0] instanceof Element);    //true
    
            console.log(oDiv.childNodes[0] instanceof Node);    //true
            console.log(oDiv.childNodes[0] instanceof Element);    //false
    
            console.log(typeof oDiv.childNodes[0].children);    //undefined
            console.log(typeof oDiv.childNodes[0].childNodes);    //object
        </script>
    </body>
    </html>
    

    通过上面的代码我们可以看到,Element的children[0]仍为Element,是Node和Element的实例,Node的childNdoes[0]为Node,只是Node的实例,不是Element的实例。

    同时,Node的children属性为为undefined

    通过以上的讲述,大家弄明白了吗?

    文章来自:https://www.cnblogs.com/jscode/archive/2012/09/04/2670819.html

  • 相关阅读:
    Android的数据存储
    Servlet第一天
    JavaScript高级程序设计读书笔记(3)
    Interesting Papers on Face Recognition
    Researchers Study Ear Biometrics
    IIS 发生意外错误 0x8ffe2740
    Father of fractal geometry, Benoit Mandelbrot has passed away
    Computer vision scientist David Mumford wins National Medal of Science
    Pattern Recognition Review Papers
    盒模型bug的解决方法
  • 原文地址:https://www.cnblogs.com/KillBugMe/p/12462660.html
Copyright © 2011-2022 走看看