原生 js 不支持 before() 和 after(),需用 insertadjacenthtml() 的 beforebegin/afterend 参数实现外部插入:beforebegin 插入目标元素前作为兄弟节点,afterend 插入其后作为兄弟节点,要求目标元素已有父节点。

用 before() 和 after() 在元素外部插入(原生 JS 不支持)
原生 JavaScript 没有 before() 和 after() 方法——这是 jQuery 提供的便捷封装。如果你直接写 element.before(...),现代浏览器会报错:TypeError: element.before is not a function。
想在元素外部前后插入,必须用原生 DOM API 的 insertAdjacentHTML() 或 insertAdjacentElement()。
-
beforebegin:插在目标元素自身之前(同级,作为前一个兄弟节点) -
afterend:插在目标元素自身之后(同级,作为后一个兄弟节点)
示例:
const btn = document.querySelector('button');
btn.insertAdjacentHTML('beforebegin', '<div class="tip">提示文字</div>');
btn.insertAdjacentHTML('afterend', '<p>后续说明</p>');
insertAdjacentHTML() 四个位置参数的实际效果
很多人混淆 afterbegin / beforeend(内部)和 beforebegin / afterend(外部)。只关注“外部”时,只需记住:
-
beforebegin→ 插到目标元素标签**前面**(不是里面),等价于 jQuery 的before() -
afterend→ 插到目标元素标签**后面**(不是里面),等价于 jQuery 的after()
注意:beforebegin 和 afterend 要求目标元素**已有父节点**,否则会抛出 DOMException: The node before which the new node is to be inserted is not a child of this node. 错误。
为什么不用 innerHTML += 或 appendChild() 做外部插入
innerHTML += 只能操作**内部内容**,它修改的是父元素的子节点列表,无法把新内容变成目标元素的兄弟节点。
appendChild() 只能把节点加到某个父元素的末尾,你得先拿到目标元素的 parentNode,再决定插在它前面还是后面——这比 insertAdjacentHTML() 多两步且易出错:
const target = document.querySelector('.item');
const parent = target.parentNode;
const newDiv = document.createElement('div');
newDiv.textContent = '外部插入';
// 想插在 target 前面?得手动找前一个兄弟或用 insertBefore
parent.insertBefore(newDiv, target);
// 想插在后面?得用 nextSibling,但可能为 null
parent.insertBefore(newDiv, target.nextSibling);
而 insertAdjacentHTML() 一行搞定,语义清晰,不依赖 parentNode 是否存在(只要目标元素已挂载)。
兼容性与 XSS 风险提醒
insertAdjacentHTML() 自 IE6 起就支持,现代所有浏览器完全可用,比 append()/prepend() 兼容性好得多(后者不支持 IE)。
但它直接解析 HTML 字符串,如果插入内容含用户输入,必须提前转义:
- 不要写
element.insertAdjacentHTML('beforebegin', '<div>' + userInput + '</div>') - 应改用
insertAdjacentText()插纯文本,或对userInput手动转义(如用document.createTextNode()创建再插入)
真正容易被忽略的点是:beforebegin 和 afterend 插入的是**兄弟节点**,它们不会改变目标元素自身的结构,但会改变其父容器的子节点顺序——这点在做动态列表渲染或动画重排时,常引发意料之外的布局跳变。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











