JS-Web-API
DOM节点获取
document.getElementsByTagName()
document.getElementsByClassName()
document.getElementsById()
document.querySelectAll()
const node = document.getElementsById(‘#dom‘)
获取DOM的property
修改dom元素的js变量,不会体现到html结构中
const node = document.getElementsById(‘#dom‘)
node.style
node.className
node.nodeName
node.nodomdeType
获取DOM的attribute
修改dom节点属性,可以在标签中看到添加或者修改属性,体现到html结构中
const node = document.getElementsById(‘#dom‘)
node.getAttribute(属性名)
node.setAttribute(属性名,属性值)
node.setAttribute(‘style’,“font-size: 15px ;”)
属性值:string
property&attribute两者都会使DOM重新渲染
新建节点
document.createElement()
插入节点
node.appendChild()
移动已有节点
//移动已有节点p2,注意是移动!将DOM移动到指定节点中,原来位置没有p2
const p2 = document.getElementById('p2')
div1.appendChild(p2)
获取父元素
node.parentNode
获取子元素
node.childNodes
删除节点
node.removeChild()
DOM性能
- DOM操作非常昂贵,避免频繁操作
- 对DOM查询做缓存
- 将频繁操作改为一次性操作
对DOM查询做缓存
// 不缓存DOM查询结果
for(let i = 0; i < document.getElementsByTagName('p').length; i++) {
// 每次循环,都会计算length,频繁进行DOM查询
}
// 缓存DOM查询结果
const pList = document.getElementsByTagName('p')
const length = pList.length
for(let i = 0; i < length; i++) {
// 缓存length,只进行一次DOM查询
}
将频繁操作改为一次性操作
document.createElementFragment
const listNode = document.getElementById('list')
// 创建一个文档片段,还没有插入到DOM树中
const frag = document.createDocumentFragment()
// 执行插入,进行整体插入,减少频繁操作
for(let i = 0; i < 10; i++) {
const li = document.createElement('li')
li.innerHTML = 'list item ' + i
frag.appendChild(li)
}
// 都完成之后,再插入到DOM树中
listNode.appendChild(frag)