【面试回顾】DOM相关常见问题总结

DOM

  • 框架的应用广泛,封装了DOM操作
  • DOM本质——树(数据结构)

DOM节点操作

  • 获取DOM节点

    
    
        
            
            
            
            dom 演示
    
            
        
        
            

    一段文字 1

    一段文字 2

    一段文字 3

    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] )

你可能感兴趣的:(前端面试dom)