IE 8: remove node save children

I am trying to remove a node from a dom tree using javascript while preserving it. I tested the three approaches shown below and they work fine in Firefox, but not in IE 8 (see Example below).

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); } 

Node input example:

 <span class="A1"> start text <span class="F"> bold text </span> end text </span> 

what this should result in:

  start text <span class="F"> bold text </span> end text 

What IE 8 does:

  start text <span class="F"> </span> end text 

As you can see, IE ignores / removes nested children.

I would be grateful for any help :)

+4
source share
4 answers

This should be easy to do as follows:

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

Look at the action .

+3
source

Use expand () for what it is intended.

 <span class="A1"> start text <span class="F"> bold text </span> end text </span> <script> jQuery(function($){$('.F').unwrap();}); </script> 
+3
source

@Jon approach, without iteration:

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

Look in action.


@ Dr.Molle's answer should be accepted.

+2
source

The following is the simplest and fastest native javascript code:

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

http://jsfiddle.net/N3J7K/

+2
source

Source: https://habr.com/ru/post/1435874/


All Articles