获取元素
window.idxxx // idxxxx
document.getElementById('idxxx')
document.getElementsByTagName('div')[0]
document.getElementsByClassName('red')[0]
document.querySelector('#idxxx')
document.querySelectorAll('.red')[0]
document.documentElement // 获取html元素
document.head // 获取head元素
document.body // 获取body元素
window // 获取窗口
document.all // 获取所有元素 (第六个falsy值)
元素的6层原型链

第一层原型:
HTMLDivElement.prototype
第二层原型:HTMLElement.prototype
第三层原型:Element.prototype
第四层原型:Node.prototype
第五层原型:EventTarget.prototype
第六层原型:Object.prototype
增删改查
- 增
// 创建一个标签节点
let div1 = document.createElement('div')
document.createElement('style')
document.createElement('script')
document.createElement('li')
// 创建一个文本节点
text1 = document.createTextNode('你好')
// 标签里面插入文本
div1.appendChild(text1)
div1.innerText = 'hello'
div1.textContent = 'hi'
// 标签插入到页面,必须插入到head或body中才会生效
document.body.appendChild(div)
已在页面中的元素.appendChild(div)
Test:页面中有
div#test1
和div#test2
,div最终出现在何处?
答案: test2里面,因为一个元素不能出现在两个地方,除非复制一份
let div = document.createElement('div')
test1.appendChild(div)
test2.appendChild(div)

- 删
parentNode.removeChild(childNode)
childNode.remove()

- 改


<div id="test">fafa</div>
console.log(test.onclick)
test.onclick= function(x){
console.log(this)
console.log(x)
}
div.onclick
默认为null
,默认点击div
不会有任何事情发生,但是把div.onclick
改为一个函数fn
。那么点击div
时浏览器就会调用函数fnfn.call(div,event)
div被当做this,event则包含了点击事件的所有信息

// 改文本内容
div.innerText = 'xxx'
div.textContent = 'xxx'
// 改HTML内容
div.innerHTML = ‘<strong>aa</strong>’
// 改标签
div.innerHTML = ‘’ // 先清空
div.appendChild(div2) // 再加内容
- 查
// 查看父元素
node.parentNode
node.parentElement
// 查看子元素
node.children
node.childNodes // 包括文本节点
// 查看子代
node.childNodes
node.children
// 查看第一个子元素
node.firstChild
node.firstElementChild
// 查看最后一个子元素
node.lastChild
node.lastElementChild
// 查看上一个元素
node.previousSibing
node.previousElementSibling
// 查看下一个元素
node.nextSibing
node.nextElementSibling
// 查看同一父元素的元素
node.parentElement.children
node.parentNode.childNodes
// 遍历div里面所有元素
travel = (node,fn) =>{
fn(node)
if(node.children){
for(let i=0;i<node.children.length;i++){
travel(node.children[i],fn)
}
}
}
travel(div1,(node)=>console.log(node))



DOM操作跨线程
- 跨线程操作
JS引擎不能操作页面,只能操作JS
渲染引擎不能操作JS,只能操作页面
document.body.appendChild(div1)
是如何改变页面的?
当浏览器发现JS在body里面加个个div1对象,浏览器就会通知渲染引擎在页面里面也新增一个div元素,新增的div元素所有属性都照抄div1对象

- 属性同步
标准属性:对标准属性的修改,会被浏览器同步到页面中
data-*属性:同上
非标准属性:对非标准属性的修改,只会停留在JS线程中,不会同步到页面


网友评论