纯JS为DOM添加html字符串:appendHTML方法和prependHTML方法 博客分类: JS jsappendprepend
程序员文章站
2024-03-15 00:01:17
...
appendHTML:
HTMLElement.prototype.appendHTML = function(html) { var divTemp = document.createElement("div"), nodes = null // 文档片段,一次性append,提高性能 , fragment = document.createDocumentFragment(); divTemp.innerHTML = html; nodes = divTemp.childNodes; for (var i=0, length=nodes.length; i<length; i+=1) { fragment.appendChild(nodes[i].cloneNode(true)); } this.appendChild(fragment); // 据说下面这样子世界会更清净 nodes = null; fragment = null; };
prependHTML:
var prependHTML = function(el, html) { var divTemp = document.createElement("div"), nodes = null , fragment = document.createDocumentFragment(); divTemp.innerHTML = html; nodes = divTemp.childNodes; for (var i=0, length=nodes.length; i<length; i+=1) { fragment.appendChild(nodes[i].cloneNode(true)); } // 插入到容器的前面 - 差异所在 el.insertBefore(fragment, el.firstChild); // 内存回收? nodes = null; fragment = null; };
转自:http://www.zhangxinxu.com/wordpress/2013/05/js-dom-basic-useful-method/