JS實(shí)現(xiàn)jQuery的append功能
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;};測(cè)試下效果
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);效果

另外, 如果想實(shí)現(xiàn)在上方插入的話, 只需要把代碼里的this.appendChild(fragment); 改為 this.insertBefore(fragment, this.firstChild);
另一種方法var div2 = document.querySelector('#div2'); div2.insertAdjacentHTML('beforebegin','<p>hello world</p>');//在調(diào)用元素外部前面添加一個(gè)元素 div2.insertAdjacentHTML('afterbegin','<p>hello world</p>');//在調(diào)用元素的內(nèi)部添加一個(gè)子元素并取代了第一個(gè)子元素 div2.insertAdjacentHTML('beforeend','<p>hello world</p>');//在調(diào)用元素內(nèi)部后面添加一個(gè)子元素 即取代了最后的子元素 div2.insertAdjacentHTML('afterend','<p>hello world</p>');//在調(diào)用元素的外部后面添加一個(gè)元素
瀏覽器的渲染的效果:

此方法是ie 的最早的方法所以兼容性特別好
以上就是JS實(shí)現(xiàn)jQuery的append功能的詳細(xì)內(nèi)容,更多關(guān)于JS 實(shí)現(xiàn)jQuery append的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Java如何基于反射機(jī)制獲取不同的類2. Android table布局開發(fā)實(shí)現(xiàn)簡單計(jì)算器3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. IntelliJ IDEA安裝插件的方法步驟5. php模擬實(shí)現(xiàn)斗地主發(fā)牌6. 理解PHP5中static和const關(guān)鍵字7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. python 代碼實(shí)現(xiàn)k-means聚類分析的思路(不使用現(xiàn)成聚類庫)9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. PHP安全-命令注入

網(wǎng)公網(wǎng)安備