DOM 编程
DOM非常难用,通常我们不使用DOM,本文记录了一些DOM的API
获取元素/标签
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 
 | document.getElementById('idxxx')
 document.getElementsByTagName('div')[0]
 document.getElementsByClassName('red')[0]
 
 
 window.idxxx
 idxxx
 document.querySelector('#idxxx')
 document.querySelectorAll('#idxxx')
 
 
 
 document.documentElement
 
 document.head
 
 document.body
 
 document.all
 
 | 
元素的原型链
一个DIV的原型链
- 
HTMLDivElement.prototype 
- 
HTMLElement.prototype 
- 
Element.prototype 
- 
Node.prototype 
- 
EventTarget.prototype 
- 
Object.prototype 
x.nodeType
Node有以下几种:
- 
1    元素Element | 标签Tag 
- 
3    文本Text 
- 
8    注释Comment 
- 
9    文档Document 
- 
11   文档片段DocumentFragment 
- 
…  … 
增删改查
增
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | let div1 = document.createElement('div')
 document.createElement('style')
 document.createElement('script')
 document.createElement('li')
 
 
 text1 = document.createTextNode('hi')
 
 
 div1.appendChild(text1)
 div1.innerText = 'hi'
 div1.textContent = 'hi'
 
 
 document.body.appendChild(div)
 已在页面中的元素.appendChild(div)
 
 
 | 
删
改
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 
 | div.className = 'red blue'
 div.classList.add('red')
 
 
 div.style = 'width:100px;color:blue'
 div.style.width = '200px'
 div.style.backgroundColor = 'white'
 
 
 div.dataset.x = 'abc'
 
 
 div.classList
 a.href
 div.getAttribute('class')
 a.getAttribute('href')
 
 
 div.innerText = 'xxx'
 div.textContent = 'xxx'
 
 
 div.innerHTML = '<strong>importent</strong>'
 
 
 div.innerHTML = ''
 div.appendChild(div2)
 
 
 newParent.appendChild(div)
 
 
 | 
查
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 
 | node.parentNode | node.parentElement
 node.parentNode.parentNode
 
 
 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)
 }
 }
 }
 
 
 | 
DOM 特性
DOM 操作跨线程
JS引擎需要通过渲染引擎操作页面
属性同步
如果有自定义属性需要在修改后被同步到页面中,需要使用data-作为前缀
property 和 attribute 的异同
两者都表示属性:
property:JS线程理解的属性
attribute:渲染引擎理解的属性
区别:
attribute只支持字符串
property支持字符串、布尔等多种类型
注意:
大部分时候同名的attribute和property值相等。如果不是标准属性,那么这两个属性值只在一开始时相等