JS实现innerafter

实现 innerAfter 方法
innerAfter 是一个自定义的 DOM 操作方法,用于在指定元素的内部内容之后插入新的内容。这与标准的 after 方法不同,后者是在元素外部插入内容。以下是实现方法:

Element.prototype.innerAfter = function(content) {
if (typeof content === 'string') {
this.insertAdjacentHTML('beforeend', content);
} else if (content instanceof Node) {
this.appendChild(content);
}
return this;
};
使用示例
// 插入字符串
document.getElementById('myElement').innerAfter('<div>New content</div>');
// 插入DOM节点
const newNode = document.createElement('div');
newNode.textContent = 'New node';
document.getElementById('myElement').innerAfter(newNode);
方法说明
insertAdjacentHTML用于插入HTML字符串,beforeend参数表示在元素内部的末尾插入appendChild用于插入DOM节点- 方法返回元素本身,支持链式调用
兼容性处理
如果需要支持旧版浏览器,可以添加以下polyfill:
if (!Element.prototype.insertAdjacentHTML) {
Element.prototype.insertAdjacentHTML = function(position, html) {
const div = document.createElement('div');
div.innerHTML = html;
const nodes = Array.from(div.childNodes);
switch(position) {
case 'beforeend':
nodes.forEach(node => this.appendChild(node));
break;
// 其他情况处理...
}
};
}
注意事项
- 插入内容会作为元素的最后一个子节点
- 大量DOM操作时建议使用DocumentFragment提高性能
- 确保目标元素存在且是合法的DOM元素






