首先我们认识一下DOM
DOM是JavaScript中很重要的一部分
一.DOM继承树
document.proto–>HTMLDocument.prototype–>Document.prototype–>Node.prototype–>EventTarget.prototype–>Object.prototype
二.DOM继承规则
- getElementById方法定义在Document.prototype上,即Element节点上不能使用
- getElementsByName方法定义在HTMLDocument.prototype上,即非html中的document不能使用(xml document,Element)
- getElementsByTagName方法定义在Document.prototype和Element.prototype上
- HTMLDocument.prototype定义了一些常用的属性,body,head
document.body //<body></body>
document.head //<head></head>
- Document.prototype上定义了documentElement属性,在HTML文档中,document.documentElement --><html></html>
- getElementByClassName、querySelectorAll、querySelect在Document.prototype,Element.prototype上均有定义
三.dom基本操作
1.创建一个节点
- document.createElement();创建元素节点
- document.createTextNode();创建文本节点
- document.createComment();创建注释节点
- document.createDocumentFragment();创建文档节点片段
document.createDocumentFragment();用法
var fragment = document.createDocumentFragment();
for(var i = 0; i<3;i++){
var li = document.createElement('li');
fragment.appendChild(li);
}
ul.appendChild(fragment);
2.插入节点
- parentNode.appendChild(child)
参数child为添加的子节点,类似push - parentNode.insertBefore(child,指定元素)
插入到指定的元素前面
3.删除节点
- parentNode.removeChild(child)
从父元素中删除一个子节点,返回删除的节点
4.替换节点
parentNode.replaceChild(new,origin);
5.复制节点
node.cloneNode()
var copyli = ul.children[0].cloneNode();//复制节点
ul.appendChild(copyli);//添加节点
注意:如果cloneNode()参数为空或者为false,则为浅拷贝,即只克隆复制节点本身,不克隆里面的子节点。如果为true,则为深拷贝