javascript DOM操作中的insertAdjacentHTML方法

插入HTML内容与文本内容以前用的是innerHTML与innerText方法,今天微博上看到这篇文章,重新勾起对insertAdjacentHTML和 insertAdjacentText方法回忆,以前网上有个比较靠谱的兼容方法:

/**
 * @param {HTMLElement} el
 * @param {String} where beforeBegin、afterBegin、beforeEnd、afterEnd
 * @param {String} html
 */
function insertHTML(el, where, html) {
	if (!el) {
		return false;
	}
	
	where = where.toLowerCase();
	
	if (el.insertAdjacentHTML) {//IE
		el.insertAdjacentHTML(where, html);
	} else {
		var range = el.ownerDocument.createRange(),
			frag = null;
		
		switch (where) {
			case "beforebegin":
				range.setStartBefore(el);
				frag = range.createContextualFragment(html);
				el.parentNode.insertBefore(frag, el);
				return el.previousSibling;
			case "afterbegin":
				if (el.firstChild) {
					range.setStartBefore(el.firstChild);
					frag = range.createContextualFragment(html);
					el.insertBefore(frag, el.firstChild);
				} else {
					el.innerHTML = html;
				}
				return el.firstChild;
			case "beforeend":
				if (el.lastChild) {
					range.setStartAfter(el.lastChild);
					frag = range.createContextualFragment(html);
					el.appendChild(frag);
				} else {
					el.innerHTML = html;
				}
				return el.lastChild;
			case "afterend":
				range.setStartAfter(el);
				frag = range.createContextualFragment(html);
				el.parentNode.insertBefore(frag, el.nextSibling);
				return el.nextSibling;
		}
	}
}

在还没开始用jQuery之前,一直用这个方法。当然后来用了jQuery的.append().appendTo().html().prepend().prependTo().text().after().before().insertAfter().insertBefore()也很方便。

insertAdjacentHTML和 insertAdjacentText这两个方法很灵活,可以在指定的地方插入html内容和文本内容,在大部分情况下比element.innerHTML的性能更好,比Document Fragments更好的HTML文档插入方案,因为我们知道Document Fragments在某些IE版本中的表现不好。
insertAdjacentText方法与 insertAdjacentHTML方法类似,只不过只能插入纯文本,参数相同。

MDN上查了一下兼容性:

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0 8.0 (8.0) 4.0 7.0 4.0 (527)

接口也很简单:

element.insertAdjacentHTML(position, text);

需要传入字符串参数position,以及字符串参数html代码。我们可以对照jQuery的HTML插入方法。
参数position 的取值:

  • beforeBegin:在该元素前插入
  • afterBegin:在该元素第一个子元素前插入
  • beforeEnd:在该元素最后一个子元素后面插入
  • afterEnd:在该元素后插入

方法同意支持空元素,和innerHTML与innerText方法没什么区别了。

性能测试可以看这里:

赞(0) 打赏
未经允许不得转载:WEBTian开发 » javascript DOM操作中的insertAdjacentHTML方法

评论 2

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #-49

    来膜拜了,学子了。

    4年前 (2014-08-26)回复

Tian开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏