DOM(文档对象)、BOM(浏览器对象)

2020-11-26  本文已影响0人  苹果咏

DOM

获取DOM节点

document.getElementById  //ID
document.getElementsByTagName  //节点
document.getElementsByClassName   //class
document.querySelector   // 可以是ID、class、节点
document.querySelectorAll  //获取所有节点,可以是ID、class、节点

DOM节点的property,修改对象属性,不会提现到html结构

p.style.width
p.className
p.nodeName
p.nodeType   // 类型,一般是1

DOM节点的attribute,修改html节点属性,会改变html结构

a.getAttribute('class')    // 获取class名称
a.getAttribute('id')
a.getAttribute('data-name')
a.setAttribute('data-name', 'koop')   // 添加一个属性
a.setAttribute('style', 'color:red') 

上面两者都可能引起DOM重新渲染


插入节点
const div1 = document.getElementById('div1')
const p1 = document.createElement('p') // 新建节点
p1.innerHtml = 'this is p1'  // 节点内容
div1.appendchild(p1)   // p1作为子节点插入div1中
父节点.insertBefore(新节点, 参考节点)   // 指定位置插入,会插入在参考节点之前
获取子元素、父元素列表
div1.childNodes   //子元素列表
div1.parentNode //父元素列表
const div1ChildNodesP = Array.prototype.slice.call(div1.childNodes).filter(child =>{
    if(child.nodeType === 1){
          return true
    }
    return false
})   // 过滤出正常的节点,不要单独文本的

删除子元素

const child  = div1.childNodes
div1.removeChild(child[0])
DOM插入性能优化
const listNode = document.getElementById('list')
// 插入一个文档片段,此时还没有插入到DOM书中
const frag = document.createDocumentFragment()
// 执行插入
for (let x = 0; x < 10; x++) {
    const li = document.createElement("li")
    li.innerHTML = "List item" + x
    frag.appendChild(li)
}
// 都完成后,最后插入到DOM树中
listNode.appendChild(frag)

对DOM查询做缓存

// 对DOM查询做缓存
const pList = document.getElementsByTagName("p")
const pLength = pList.length
for (let i = 0; i < pLength; i++) {
    // 缓存length ,只进行一次DOM查询 
}



BOM

// navigator浏览器信息
const ua = navigator.userAgent
const isChrome = ua.indexOf("Chrome")
console.log(isChrome)

// screen
console.log(screen.width)
console.log(screen.height)

// location
location.href    // 网页地址
location.host   // 域名
location.protocol    //  http  还是  https
location.pathname    //后缀名  /wiki/10229108211493
location.search    // ?后面的内容
location.hash    // #后面的内容

//history
history.back()
history.forward()

BOM常用对象
操作DOM

上一篇 下一篇

猜你喜欢

热点阅读