js实现unwrap
实现 unwrap 功能的方法
在 JavaScript 中,unwrap 通常指移除元素的父节点,但保留其子节点和内容。以下是几种实现方式:
使用原生 DOM 操作
function unwrap(element) {
const parent = element.parentNode;
while (element.firstChild) {
parent.insertBefore(element.firstChild, element);
}
parent.removeChild(element);
}
使用 jQuery 的 unwrap 方法
如果项目中已引入 jQuery,可以直接使用其内置方法:

$('.target-element').unwrap();
处理多个元素的情况
对于需要批量处理的场景:

function unwrapAll(selector) {
document.querySelectorAll(selector).forEach(el => {
const parent = el.parentNode;
Array.from(el.childNodes).forEach(child => {
parent.insertBefore(child, el);
});
parent.removeChild(el);
});
}
注意事项
- 操作前应检查父节点是否存在
- 文本节点和注释节点也会被保留
- 该方法不会破坏事件监听器
Polyfill 方案
对于需要兼容旧浏览器的环境:
if (!Element.prototype.unwrap) {
Element.prototype.unwrap = function() {
this.replaceWith(...this.childNodes);
return this;
};
}
这些方法可以根据具体需求选择使用,原生 DOM 操作适合轻量级项目,jQuery 版本适合已有 jQuery 依赖的项目,而 Polyfill 方案则提供了标准的扩展方式。






