DOM

  • 框架的利用宽泛,封装了DOM操作
  • DOM实质——树(数据结构)

DOM节点操作

  • 获取DOM节点

    <!DOCTYPE html><html lang="en">    <head>        <meta charset="UTF-8">        <meta name="viewport" content="width=device-width, initial-scale=1.0">        <meta http-equiv="X-UA-Compatible" content="ie=edge">        <title>dom 演示</title>        <style>            .container {                border: 1px solid #ccc;            }            .red {                color: red;            }        </style>    </head>    <body>        <div id="div1" class="container">            <p id="p1">一段文字 1</p>            <p>一段文字 2</p>            <p>一段文字 3</p>        </div>        <div id="div2">            <img src="https://img3.mukewang.com/5a9fc8070001a82402060220-100-100.jpg"/>        </div>        <ul id="list">        </ul>        <script src="./dom-1.js"></script>    </body></html>
    const div1 = document.getElementById('div1')console.log('div1', div1)const divList = document.getElementsByTagName('div') // 汇合console.log('divList.length', divList.length)console.log('divList[1]', divList[1])const containerList = document.getElementsByClassName('container') // 汇合console.log('containerList.length', containerList.length)console.log('containerList[1]', containerList[1])const pList = document.querySelectorAll('p')console.log('pList', pList)const pList = document.querySelectorAll('p')const p1 = pList[0]

DOM节点的 property/attribute

// property 模式const pList = document.querySelectorAll('p')const p1 = pList[0]p1.style.width = '100px'console.log( p1.style.width )p1.className = 'red'console.log( p1.className )console.log(p1.nodeName) // Pconsole.log(p1.nodeType) // 1// attributep1.setAttribute('data-name', 'datetime')console.log( p1.getAttribute('data-name') )p1.setAttribute('style', 'font-size: 50px;')console.log( p1.getAttribute('style') )
  • property:批改对象属性,不会体现到html构造中
  • attribute:批改html属性,会扭转html构造
  • 两者都有可能引起DOM从新渲染

新增、插入节点

const div1 = document.getElementById('div1')const div2 = document.getElementById('div2')// 新建节点const newP = document.createElement('p')newP.innerHTML = 'this is newP'// 插入节点div1.appendChild(newP)// 挪动节点const p1 = document.getElementById('p1')div2.appendChild(p1)// 获取父元素console.log( p1.parentNode )// 获取子元素列表const div1ChildNodes = div1.childNodesconsole.log( div1.childNodes )const div1ChildNodesP = Array.prototype.slice.call(div1.childNodes).filter(child => {    if (child.nodeType === 1) {        return true    }    return false})console.log('div1ChildNodesP', div1ChildNodesP)div1.removeChild( div1ChildNodesP[0] )