IE 8:删除节点保留子节点

我试图使用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); } 

示例输入节点:

  start text  bold text  end text  

它应该导致什么:

  start text  bold text  end text 

IE 8的作用:

  start text   end text 

如您所见,IE忽略/删除嵌套的子项。

我很感激任何帮助:)

它应该很容易做到这样:

 function removeKeepChildren(node) { var $node = $(node); $node.contents().each(function() { $(this).insertBefore($node); }); $node.remove(); } 

看到它在行动

使用unwrap() ,这就是它的目的。

  start text  bold text  end text   

@ Jon的方法,没有迭代:

 function removeKeepChildren(node) { var $node = $(node); var contents = $node.contents(); $node.replaceWith(contents); } 

看到它在行动。


@ Dr.Molle的答案应该是公认的答案。

接下来是最简单和最快速的本机JavaScript代码:

 function removeNodeKeepChildren(node) { if (!node.parentElement) return; while(node.firstChild) { node.parentElement.insertBefore(node.firstChild, node); } node.parentElement.removeChild(node); } 

http://jsfiddle.net/N3J7K/