创建元素的三种方式:
1.document.write() 【document.write ('新设置的内容<p>标签也可以生成</p>')】
2.innerHTML var box = document.getElementById('box');
box.innerHTML = '新内容<p>新标签</p>';
3.document.createElement()
innerHTML方法由于会对字符串进行解析,需要避免在循环内多次使用。
可以借助字符串或数组的方式进行替换,再设置给innerHTML
优化后与document.createElement性能相近
节点操作:
var body = document.body;
var div = document.createElement('div');
body.appendChild(div);
var firstEle = body.children[0];
body.insertBefore(div,firstEle);
body.removeChild(firstEle);
var text = document.createElement('p');
body.replaceChild(text, div);
节点层级:【父子属性,兄弟属性】
var box = document.getElementById('box');
console.log(box.parentNode);
console.log(box.childNodes);
console.log(box.children);
console.log(box.nextSibling);
console.log(box.previousSibling);
console.log(box.firstChild);
console.log(box.lastChild);
【
childNodes和children的区别,childNodes获取的是子节点,children获取的是子元素
nextSibling和previousSibling获取的是节点,获取元素对应的属性是nextElementSibling和previousElementSibling获取的是元素
nextElementSibling和previousElementSibling有兼容性问题,IE9以后才支持
】
节点操作,方法
appendChild()
insertBefore()
removeChild()
replaceChild()
节点层次,属性
parentNode
childNodes
children
nextSibling/previousSibling
firstChild/lastChild