JS實現(xiàn)jQuery的append功能
更新時間:2021年05月28日 10:44:45 作者:Beater
jQuery中可以直接使用$el.append()為元素添加字符串型dom, 但是最近轉(zhuǎn)戰(zhàn)Vue, 再使用jQuery明顯不合適了, 所以通過查找資料, 封裝一個可以實現(xiàn)同樣效果的方法.
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
另外, 如果想實現(xiàn)在上方插入的話, 只需要把代碼里的this.appendChild(fragment); 改為 this.insertBefore(fragment, this.firstChild);
另一種方法
var div2 = document.querySelector("#div2"); div2.insertAdjacentHTML("beforebegin","<p>hello world</p>");//在調(diào)用元素外部前面添加一個元素 div2.insertAdjacentHTML("afterbegin","<p>hello world</p>");//在調(diào)用元素的內(nèi)部添加一個子元素并取代了第一個子元素 div2.insertAdjacentHTML("beforeend","<p>hello world</p>");//在調(diào)用元素內(nèi)部后面添加一個子元素 即取代了最后的子元素 div2.insertAdjacentHTML("afterend","<p>hello world</p>");//在調(diào)用元素的外部后面添加一個元素
瀏覽器的渲染的效果:
此方法是ie 的最早的方法所以兼容性特別好
以上就是JS實現(xiàn)jQuery的append功能的詳細內(nèi)容,更多關(guān)于JS 實現(xiàn)jQuery append的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用bootstrap validator的remote驗證代碼經(jīng)驗分享(推薦)
這篇文章主要介紹了使用bootstrap validator的remote驗證器驗證經(jīng)驗分享(推薦)的相關(guān)資料,本文介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下2016-09-09