Web API—DOM(二)

本文详细介绍了DOM节点操作,包括节点属性、父子节点、兄弟节点以及节点操作方法。同时,讲解了DOM事件操作,如addEventListener、事件流三阶段、事件对象以及事件委托的应用。通过实例展示了如何动态创建列表、表格,以及处理事件监听和解除。此外,还探讨了offset和client系列属性在处理元素位置和大小时的作用。
摘要由CSDN通过智能技术生成

DOM-Web API

DOM节点操作

在这里插入图片描述

节点属性
 var box = document.getElementById("box");
 // 元素节点
 console.dir(box); 
 //nodeName: "DIV", nodeType: 1, nodeValue: null
 // 属性节点获取
 var idnode = box.getAttributeNode("id");
 console.dir(idnode); 
 //nodeName: "id", nodeType: 2, nodeValue: "box"
 idnode.nodeValue = "demo";
// 文本节点
 var childnodes = box.childNodes;
 console.log(childnodes); 
 //nodeName: "#text", nodeType: 3, nodeValue: "div 1"
 childnodes[0].nodeValue = "child 1"; //得到的下标是0
  • nodeType节点的类型
    • 属性值是数字,表示不同的节点类型共12种,只读
    • 1元素节点 2属性节点 3文本节点
  • nodeName节点的名称(只读)
  • nodeValue节点值
    • 返回或设置当前节点的值,元素节点的value始终是null
父子节点
  • childNodes

    只读属性,获取一个节点所有子节点的实时集合,动态变化

  • childeren

    只读,返回一个节点所有的子元素节点结合,动态更新

  • firstChild

    只读,返回该节点的第一个子节点,没有则返回null

  • lastChild

    只读,返回该节点的最后一个子节点,没有返回null

  • parentNode

    返回一个当前节点的父节点

  • parentElement

    返回一个当前节点的父元素节点

var box = document.getElementById("box");
        console.log(box.childNodes); //NodeList(5) [text, p, text, span, text]获取所有类型的子节点,其中text中保存的是换行
        console.log(box.children); //HTMLCollection(2) [p, span]获取所有元素类型的子节点
        console.log(box.firstChild); //#text所有类型的第一个
        console.log(box.lastElementChild); //<span>span小盒子</span>所有元素类型的最后一个
        console.log(box.parentNode); //<body>……</body>
        console.log(box.parentElement); //<body>……</body>
兄弟节点
  • nextSibling

    只读,返回与该节点同级的下一个节点,无则返null

  • previousSibling

    只读,返回与该节点同级的上一个节点,无则返null

  • nextElementSibling

    返回的是下/上一个元素节点(IE9以后才兼容)

  • previousElementSibling

var p3 = my$("p3");
        console.log(p3.nextSibling); //#text
        console.log(p3.nextElementSibling); // <p>这是段落4</p>
        console.log(p3.previousSibling); //#text
        console.log(p3.previousElementSibling); // <p>这是段落2</p>
节点操作
  • 创建节点

    • document.createElement(“div”)创建元素节点

    • document.createAttribute(“id”)创建属性节点

    • document.createTextNode(“hello”)创建文本节点

    • 一般将创建的新节点保存在变量中方便使用,创建的新的节点,是存储在内存中的,并没有添加到DOM树上

      //创建一个元素节点
      var div = document.createElement("div");
              console.dir(div); //nodeValue=1
      var id = document.createAttribute("class");
              console.dir(id); //nodeValue=2
      var txt = document.createTextNode("hello");
            
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值