您的位置:首页技术文章
文章详情页

JS实现jQuery的append功能

【字号: 日期:2024-03-24 08:07:24浏览:44作者:猪猪
目录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));})// 插入到最后 appendthis.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 的最早的方法所以兼容性特别好

以上就是JS实现jQuery的append功能的详细内容,更多关于JS 实现jQuery append的资料请关注好吧啦网其它相关文章!

标签: JavaScript
相关文章: