【笔记】 《js权威指南》- 第15章 脚本化文档 - 15.6 创建、插入和删除节点

1.创建节点:

(1).创建元素节点:

var p = document.createElement("p");

(2). 创建Text节点:

var text = document.createTextNode("abc");

(3). 复制节点:

//深度复制
var element2 = element.cloneNode(true);

其他: createComment, createElementNS, createDocumentFragment等等。


2.插入节点:

appendChild在父节点的最后插入新节点;

insertBefore在父节点的某个节点之前插入新节点;

如果使用的新节点是已经存在的子节点,那么会删除该节点将他们插入新的位置。


3.删除和替换节点:

removeChild:在父节点中删除一个节点;

replaceChild:在删除后在该位置添加一个新节点。


4.使用DocumentFragment:

创建一临时容器,如果给文档插入添加一个文档片段,那么他会将片段中的节点插入元素中,而不包括片段节点。

兼容模拟insertAdjacentHTML的Insert工具类:

var Insert = (function() {
	if (document.createElement("div").insertAdjacentHTML) {
		return {
			before : function(e, h) {
				e.insertAdjacentHTML("beforebegin", h);
			},
			after : function(e, h) {
				e.insertAdjacentHTML("afterend", h);
			},
			atStart : function(e, h) {
				e.insertAdjacentHTML("afterbegin", h);
			},
			atEnd : function(e, h) {
				e.insertAdjacentHTML("beforeend", h);
			}
		};
	}

	function fragment(html) {
		var elt = document.createElement("div");
		var frag = document.createDocumentFragment();
		elt.innerHTML = html;
		while (elt.firstChild)
		frag.appendChild(elt.firstChild);
		return frag;
	};

	var Insert = {
		before : function(e, h) {
			e.parentNode.insertBefore(fragment(html), e);
		},
		after : function(e, h) {
			e.parentNode.insertBefore(fragment(html), e.nextSibling);
		},
		atStart : function(e, h) {
			e.insertBefore(fragment(html), e.firstChild);
		},
		atEnd : function(e, h) {
			e.appendChild(fragment(html));
		}
	};

	Element.prototype.insertAdjacentHTML = function(pos, html) {
		switch(pos.toLowerCase()) {
			case "beforebegin":
				return Insert.before(this, html);
			case "afterend":
				return Insert.after(this, html);
			case "afterbegin":
				return Insert.atStart(this, html);
			case "beforeend":
				return Insert.atEnd(this, html);
		}
	};
	return Insert;
})();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值