DOM节点介绍
Node VS Element ?
Node的类型有多种,其中包含节点(Element),文本,注释。
MDN NodeType
DOM对象的增删改查
选择DOM对象(查询,选定DOM对象)
1 2 3 4 5 6 7 8 9
| document.getElementById()
document.getElementsByTagName() document.getElementsByClassName()
document.querySelector() document.querySelectorAll()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
var div1 = document.getElementById('first-div');
var trs = document.getElementById('main-table').getElementsByTagName('tr');
var reds = document.getElementById('test-div').getElementsByClassName('red');
var cs = test.children;
var first = test.firstElementChild; var last = test.lastElementChild;
var el = document.querySelector('.hide');
var el = document.querySelector('#main-table');
var el = document.querySelector("div.user-panel.main input[name='login']");
|
特定元素获取
1 2 3 4 5
| document.documentElement document.head document.body document.all
|
节点相对对象选取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| node.parentNode node.parentElement
node.parentNode.parentNode
node.parentNode.childNodes node.parentNode.children
node.previousSibling node.nextSibling
node.childNodes node.children
node.firstChild node.lastChild
|
1 2 3 4 5 6 7 8 9 10 11 12
|
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(内容增加,节点修改)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| let p = document.getElementById('p-id');
p.innerHTML = 'ABC'; p.innerHTML = 'ABC <span style="color:red"></span>XYZ';
p.innerText = 'Hello DOM'; p.innerText = '<script>alert('Hi!')</script>'; p.textContent = ''; p.textContent = '';
p.style.color = '#01234'; p.style.fontSize = '1.25em'; p.style.paddingTop = '5px';
|
1 2 3 4 5 6 7 8
| let d = document.createElement('style');
d.setAttribute('type', 'text/css');
d.innerHTML = 'p {color: red}';
document.getElementsByTagName('head')[0].appendChild(d);
|
1 2 3 4 5 6 7 8
| let list = doculment.getElementById('list'); let ref = document.getElementById('python'); let haskell = document.createElement('p');
haskell.id = 'haskell'; haskell.innerText = 'Haskell'; list.insertBefore(haskell, ref);
|
1 2 3 4 5 6 7
| var i, c, list = doculment.getElementById('list');
for(i = 0; i< list.children.length;i++){ c = list.children[i]; }
|
节点创建
1 2 3 4 5 6 7 8 9 10
| document.createElement('div') document.createElement('style') document.createElement('script')
document.createTextNode('Hello')
div_1.appendChild(TEXT_NODE) div_1.innerText = 'Hello World'
|
注意
appendChild(NODE)// 改变NODE所在位置,页面不会新增NODE
删除DOM
旧方法:
- 获取节点本身, 获取父节点
- 调用父节点
removeChild
删除节点本身
新方法:
- 获取节点本身
- 节点本身调用
remove()
删除自身
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
const parent = self.parentElement; let self = document.querySelector('#target');
let removed = parent.removeChild(self);
removed === self;
let self = document.querySelector('#target'); let removed = self.remove() removed === self;
|