目录
Show Me The Code
HTMLElement.prototype.appendHTML = function(html) { let divTemp = document.createElement("div"); let nodes = null; let fragment = document.createDocumentFragment(); divTemp.innerHTML = html; nodes = divTemp.childNodes; nodes.forEach(item => { fragment.appendChild(item.cloneNode(true)); }) // 插入到最后 append this.appendChild(fragment); // 在最前插入 prepend // this.insertBefore(fragment, this.firstChild); nodes = null; fragment = null; };
测试下效果
html
<style> .child { height: 50px; width: 50px; background: #66CCFF; margin-bottom: 1em; } </style> <div id="app"> <div class="child"> <div class="child"> </div>
js
let app = document.getElementById('app'); let child = `<div class="child">down</div>`; app.appendHTML(child);
效果
PS
另外, 如果想实现在上方插入的话, 只需要把代码里的this.appendChild(fragment); 改为 this.insertBefore(fragment, this.firstChild);
另一种方法
var div2 = document.querySelector("#div2"); div2.insertAdjacentHTML("beforebegin","<p>hello world</p>");//在调用元素外部前面添加一个元素 div2.insertAdjacentHTML("afterbegin","<p>hello world</p>");//在调用元素的内部添加一个子元素并取代了第一个子元素 div2.insertAdjacentHTML("beforeend","<p>hello world</p>");//在调用元素内部后面添加一个子元素 即取代了最后的子元素 div2.insertAdjacentHTML("afterend","<p>hello world</p>");//在调用元素的外部后面添加一个元素
浏览器的渲染的效果:
此方法是ie 的最早的方法所以兼容性特别好
以上就是JS实现jQuery的append功能的详细内容,更多关于JS 实现jQuery append的资料请关注华域联盟其它相关文章!
您可能感兴趣的文章:
- jQuery添加新内容的四个常用方法分析【append,prepend,after,before】
- 解决jQuery使用append添加的元素事件无效的问题
- jquery append与appendTo方法比较
- jquery 追加元素append、prepend、before、after用法与区别分析
- jquery在ie7下选择器的问题导致append失效的解决方法
- jquery append 动态添加的元素事件on 不起作用的解决方案
- jQuery使用append在html元素后同时添加多项内容的方法
- 解决Jquery向页面append新元素之后事件的绑定问题
- jQuery中appendTo()方法用法实例
- jQuery中append()方法用法实例
本文由 华域联盟 原创撰写:华域联盟 » JS实现jQuery的append功能
转载请保留出处和原文链接:https://www.cnhackhy.com/67361.htm