关于前端:面试回顾DOM相关常见问题总结

42次阅读

共计 2093 个字符,预计需要花费 6 分钟才能阅读完成。

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) // P
console.log(p1.nodeType) // 1

// attribute
p1.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.childNodes
console.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] )

正文完
 0