js 实现jquery append


使用原生 JavaScript 实现 jQuery 的 append 方法
jQuery 的 append 方法用于向选定的元素内部末尾插入内容。以下是几种原生 JavaScript 的实现方式:
使用 appendChild 方法
// 获取目标元素
const targetElement = document.getElementById('target');
// 创建要插入的新元素
const newElement = document.createElement('div');
newElement.textContent = 'This is appended content';
// 使用 appendChild 插入
targetElement.appendChild(newElement);
使用 insertAdjacentHTML 方法
// 获取目标元素
const targetElement = document.querySelector('.container');
// 使用 insertAdjacentHTML 在内部末尾插入 HTML
targetElement.insertAdjacentHTML('beforeend', '<div>Appended HTML</div>');
实现一个通用的 append 函数
function append(parent, content) {
if (typeof content === 'string') {
parent.insertAdjacentHTML('beforeend', content);
} else if (content instanceof Node) {
parent.appendChild(content);
}
}
// 使用示例
const container = document.getElementById('container');
append(container, '<span>Text content</span>');
append(container, document.createElement('div'));
处理多个元素的插入
// 扩展 Node 原型以添加 append 方法
Node.prototype.append = function(...nodes) {
nodes.forEach(node => {
if (typeof node === 'string') {
this.insertAdjacentHTML('beforeend', node);
} else {
this.appendChild(node);
}
});
};
// 使用示例
document.querySelector('ul').append(
'<li>Item 1</li>',
document.createElement('li')
);
注意事项
- 原生
appendChild只能插入 DOM 节点对象,不能直接插入 HTML 字符串 insertAdjacentHTML可以插入 HTML 字符串但存在 XSS 风险,使用时应对内容进行转义- 现代浏览器已支持原生
Element.append()方法,可以同时接受 DOM 节点和字符串参数
这些方法提供了类似 jQuery append 的功能,可以根据具体需求选择使用。对于需要支持旧浏览器的项目,建议使用 polyfill 或功能检测。






