一 JS如何操作DOM树
- Document Object Model,文档对象模型
- window.document,JS用document操作网页
二 获取元素(标签)
- API
window.idxxx或者直接idxxx;
document.getElementById('idxxx');
document.getElementsByTagName('div');
document.getElementsByClassName('red');
document.querySelector('#idxxx');
document.querySelectorAll('.red');
- 获取特定元素
document.documentElement
document.head
document.body
window
document.all
- 获取的元素是一个对象,以div元素为例,它的原型链分为以下六层:
HTMLDivElement.prototype
HTMLElement.prototype
Element.prototype
Node.prototype
EventTarget.prototype
Object.prototype
- 节点
节点包含元素(Element,也叫标签Tag),文本(Text),注释(Comment),文档(Document)等。
三 节点的增加操作
- 创建一个标签节点
document.createElement('div')
- 创建一个文本节点
document.createTextNode('你好')
- 插入节点
document.body.appendChild()
已在页面中的元素.appendChild()
- 执行以下代码
test1.appendChild(div)
test2.appendChild(div)
四 节点的删除操作
旧方法parentNode.removeChild()
新方法childNode.remove()
五 节点的修改操作
- 该标准属性
改class:div.className
改class:div.classList.add
改style:div.style='width:100px;color:blue;'
改style的一部分:div.style.backGroundColor
改data-*属性:div.dataset.x
- 读标准属性
div.classList/a.href
div.getAttribute('class')/a.getAttribute('href')
- 改事件处理函数
div.onclick默认为null
- 改内容
div.innerText
div.textContent
- 改html内容
div.innerHTML
- 改标签
div.innerHTML=''
div.appendChild(newdiv)
- 改父级元素
newParent.appendChild(div)
六 节点的查询操作
node.parentNode
node.parentElement
node.childNodes
node.children
node.parentNode.childNodes
node.parentNode.children
node.firstChild
node.lastChild
node.previousSibling
node.nextSibling
travel=(node,fn)=>{
fn(node)
if(node.children){
for(let i=0;i<node.children.length;i++){
travel(node.children[i],fn)
}
}
}