js 实现 prepend
实现 prepend 的方法
在 JavaScript 中,prepend 用于在父元素的子节点列表的开头插入新节点或字符串。以下是几种实现方式:
使用 Node.prepend() 方法
现代浏览器原生支持 prepend 方法,可以直接调用:

const parent = document.getElementById('parent');
const child = document.createElement('div');
child.textContent = 'New element';
parent.prepend(child);
使用 insertBefore 方法
对于不支持 prepend 的旧浏览器,可以使用 insertBefore:
const parent = document.getElementById('parent');
const child = document.createElement('div');
child.textContent = 'New element';
parent.insertBefore(child, parent.firstChild);
插入字符串内容
prepend 也支持直接插入字符串:

const parent = document.getElementById('parent');
parent.prepend('Text content');
插入多个节点
可以一次性插入多个节点或字符串:
const parent = document.getElementById('parent');
const child1 = document.createElement('div');
const child2 = document.createElement('span');
parent.prepend(child1, child2, 'Text content');
Polyfill 实现
如果需要兼容旧浏览器,可以实现一个简单的 polyfill:
if (!Element.prototype.prepend) {
Element.prototype.prepend = function() {
const nodes = Array.from(arguments);
for (let node of nodes) {
if (typeof node === 'string') {
node = document.createTextNode(node);
}
this.insertBefore(node, this.firstChild);
}
};
}
这些方法提供了灵活的方式在 DOM 中实现 prepend 功能。






