子を保持したまま、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はネストされた子を無視/削除します。
助けていただければ幸いです:)