纯JS为DOM添加html字符串:appendHTML方法和prependHTML方法

jQuery  append() 方法中可以直接添加字符,如:$("p").append(" <b>Hello world!</b>");

怎么用js实现呢:

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;
};

 

转自:https://www.iteye.com/blog/shenchuochuo-2197445

$("p").append(" <b>Hello world!</b>");

纯JS为DOM添加html字符串:appendHTML方法和prependHTML方法

原文:https://www.cnblogs.com/7qin/p/12117251.html

上一篇:阿里程序员的2019Android年终盘点,必备技能知识点,程序员必须收藏


下一篇:CCF-CSP:201909-1小明种苹果