zoukankan      html  css  js  c++  java
  • WebAPI之DOM的节点操作 Better

    获取DOM节点

      document.getElementById('id')  // 元素

      document.getElementsByTagName('div')  // 集合

      document.getElementsByClassName('class')  // 集合

      document.querySelectorAll('.class')  // 集合

    DOM样式操作

      DOM节点的 property 形式(修改对象的属性,不会体现到html结构中)

    const pList = document.querySelectorAll('p')
    const p1 = pList[0]
    
    console.log(p1.style.width)
    console.log(p1.style)
    console.log(p1.className)
    console.log(p1.nodeName)
    console.log(p1.nodeType) // 1

      DOM节点的 attribute 形式 (修改html标签属性,会改变html结构)

    const pList = document.querySelectorAll('p')
    const p1 = pList[0]
    
    p1.getAttribute('data-name')
    p1.setAttribute('data-name', 'hello')
    p1.getAttribute('style')
    p1.setAttribute('style', 'font-size: 30px;')

    *总结:两者都有可能引起DOM重新渲染,如无必要,推荐使用property 形式。因为在JS机制中可能会减少一些不必要的重新渲染,而使用attribute 形式修改, 必定会对DOM重新渲染。

    DOM结构操作

      新增/插入节点 [ document.createElement('p')、xx.appendChild(p1) ]

    const div1 = document.getElementById('div1')
    // 添加节点
    const p1 = document.createElement('p')
    p1.innerHTML = 'this is p1'
    div1.appendChild(p1)
    // 移动已有节点
    const p2 = document.getElementById('p2')
    div1.appendChild(p2)

      获取获取父元素/ 子元素列表 [x.parentNode、x.childNodes]

    // 获取父元素
    console.log(p1.parentNode)
    
    // 获取子元素列表
    console.log(div1.childNodes)
    
    // 过滤出DOM节点
    const div1childsP = Array.prototype.slice.call(div1.childNodes).filter( child => {
      if (child.nodeType === 1) {
          return true
      }
      return false
    })
    console.log(div1childsP)

      删除子元素[  x.removeChild(child[0]) ]

    const div1 = document.getElementById('id1')
    div1.removeChild(div1.childNodes[0])

    DOM 性能优化

      对DOM查询做缓存

      将频繁的操作改为一次性操作

  • 相关阅读:
    Sql2000分页效率
    CSS笔记
    向模态窗体传递参数和获取返回值
    css 实现div 内容垂直居中
    轻量级的数据交换格式——初识Json
    CSS 绝对定位
    前台小模块CSS布局代码
    XML常用类(淘宝API)
    表单form
    js 分页
  • 原文地址:https://www.cnblogs.com/huangtq/p/14532029.html
Copyright © 2011-2022 走看看