js 实现append()
实现 append() 方法
在 JavaScript 中,append() 方法用于向 DOM 元素的子节点列表末尾添加一个或多个节点或字符串。以下是几种实现方式:
原生 DOM 方法
现代浏览器原生支持 append() 方法,可以直接使用:
const parentElement = document.getElementById('parent');
const newElement = document.createElement('div');
newElement.textContent = 'New Element';
parentElement.append(newElement);
兼容性实现(Polyfill)
对于不支持 append() 的老旧浏览器,可以通过以下方式实现类似功能:
if (!Element.prototype.append) {
Element.prototype.append = function() {
const args = Array.prototype.slice.call(arguments);
const docFrag = document.createDocumentFragment();
args.forEach(function(arg) {
if (arg instanceof Node) {
docFrag.appendChild(arg);
} else {
docFrag.appendChild(document.createTextNode(String(arg)));
}
});
this.appendChild(docFrag);
};
}
jQuery 实现
如果使用 jQuery,等效的方法是 .append():
$('#parent').append('<div>New Element</div>');
数组模拟实现
对于非 DOM 环境(如普通数组),可以模拟类似功能:
Array.prototype.append = function(item) {
this.push(item);
return this;
};
const arr = [1, 2, 3];
arr.append(4); // [1, 2, 3, 4]
性能注意事项
当需要添加多个元素时,使用 DocumentFragment 比直接操作 DOM 更高效:

const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const div = document.createElement('div');
div.textContent = `Item ${i}`;
fragment.append(div);
}
document.body.append(fragment);






