1.封装获取元素节点(DOM节点)方法

写法一 数组写法

  1. <body>
  2. <div class="box" id="box" style="background-color: green;"
  3. >
  4. 我是文本节点
  5. <!-- 我是注释君 -->
  6. <h1>我是标题标签</h1>
  7. <a href="">我是超链接</a>
  8. <p>我是段落标签</p>
  9. </div>
  10. </body>
  11. <script src="./index.js"></script>
  12. <script>
  13. var div = document.getElementsByTagName('div')[0]; //
  14. // 1.元素节点 = 1
  15. // 2.属性节点 = 2
  16. // 3.文本节点 text = 3
  17. // 4.注释节点 comment = 8
  18. // 5.document = 9
  19. // 6.DocumentFragement = 11
  20. // nodeName -> 元素节点的nodeName 大写 只读
  21. // nodeValue 可写 属性、注释、文本可用
  22. // nodeType 只读
  23. function elemChildren(node){
  24. var arr = [],
  25. children = node.childNodes;
  26. for(var i = 0;i<children.length;i++){
  27. var childItem = children[i];
  28. if(childItem.nodeType===1){
  29. arr.push(childItem);
  30. }
  31. }
  32. return arr;
  33. }
  34. console.log(elemChildren(div));
  35. </script>

写法二 类数组

  1. var div = document.getElementsByTagName('div')[0];
  2. function elemChildren(node){
  3. var temp = {
  4. 'length': 0,
  5. 'push': Array.prototype.push,
  6. 'splice': Array.prototype.splice
  7. },
  8. len = node.childNodes.length;
  9. for(var i = 0;i<len;i++){
  10. var childItem = node.childNodes[i];
  11. if(childItem.nodeType === 1){
  12. temp[temp['length']] = childItem;
  13. temp['length']++;
  14. // temp.push(childItem); push方法
  15. }
  16. }
  17. return temp;
  18. }
  19. console.log(elemChildren(div));

2.document的继承出处

document 构造函数 -> HTMLDocument 构造函数 -> Document

HTMLDocument 构造出来的对象里面有proto::Document.prototype

document.proto= HTMLDocument.prototype
HTMLDocument.prototype = Document.prototype

3.DOM结构树

image.png

getElementById()

<body>    
        <div>
        <p>123</p>
    </div>
</body>
<script src="./index.js"></script>
<script>
    // DOM操作深入
    //1 getElementById()
    //来自于Document.prototype

    //2. Element.prototype HTMLElement.prototype 没有
      var div = document.getElementById('div')[0];

    var p = div.getElementById('p')[0];
    console.log(p);

 </script>

image.png
image.png
大意可以通过document获取元素a 但是无法通过元素a再获取子元素

dom div形成原理

        //div形成原理
        var div = document.getElementsByTagName('div')[0];
    <div>
        <p>123</p>
    </div> -> function HTMLDivElement() {
        div = new HTMLDivElement
    }

HTMLDivElement 继承于 HTMLElement
image.png

getElementByName()

   Document.prototype  有<br />Element.prototype 没有

道理同getElementById

getElementsByTagName getElementsByClassName querySelector querySelectorAll

Document.prototype 有
Element.prototype 有

    var div = document.getElementsByTagName('div')[0];
    var p = div.getElementsByTagName('p')[0];
    console.log(p);

image.png
原型链顶层 object.prototype
_

获取HTML head body 的原型方法

body:document.body
head:document.head
html:document.documentElment

image.png

作业