网络编程
位置:首页>> 网络编程>> JavaScript>> JS实现jQuery的append功能

JS实现jQuery的append功能

作者:Beater  发布时间:2024-04-22 22:23:00 

标签:js,append,jQuery
目录
  • Show Me The Code

  • 测试下效果

  • 效果

  • PS

  • 另一种方法

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

效果

JS实现jQuery的append功能

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>");//在调用元素的外部后面添加一个元素

浏览器的渲染的效果:

JS实现jQuery的append功能

此方法是ie 的最早的方法所以兼容性特别好

来源:https://juejin.cn/post/6966884363363418126

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com