我正在尝试使用 javascript 从 dom 树中删除一个节点,同时保留它的子节点。我测试了下面显示的 3 种方法,它们在 Firefox 中运行良好,但在 IE 8 中却不行(参见下面的示例)。
function removeNodeKeepChildren(node){
// approach 1
jQuery(node.parentNode).children().map(function (index) {
jQuery(this).replaceWith(jQuery(this).contents());
});
// approach 2
// doesn't work with content() either
jQuery(node.parentNode).html(jQuery(node).html());
// approach 3
var childfragment = document.createDocumentFragment();
for(var i=0; i<node.childNodes.length;i++){
childfragment.appendChild((node.childNodes[i]).cloneNode());
}
node.parentNode.replaceChild(childfragment,node);
}
示例输入节点:
<span class="A1">
start text
<span class="F">
bold text
</span>
end text
</span>
结果应该是什么:
start text
<span class="F">
bold text
</span>
end text
IE 8 的作用:
start text
<span class="F">
</span>
end text
如您所见,IE 会忽略/删除嵌套的子项。
如果有任何帮助,我将不胜感激:)
最佳答案
这样做应该很容易:
function removeKeepChildren(node) {
var $node = $(node);
$node.contents().each(function() {
$(this).insertBefore($node);
});
$node.remove();
}
关于javascript - 即 8 : remove node keep children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12561591/