Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE 8: remove node keep children

I am trying to remove a node from the dom tree using javascript while keeping it's children. I tested the 3 approaches shown below and they work fine in Firefox but do 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);
}

Example input node:

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

what it 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'd appreciate any help :)

like image 583
sotix Avatar asked Dec 21 '22 16:12

sotix


2 Answers

It should be easy to do like this:

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

See it in action.

like image 179
Jon Avatar answered Dec 23 '22 05:12

Jon


Use unwrap(), that's what it's intended for.

<span class="A1">
    start text
    <span class="F">
        bold text
    </span>
    end text
</span>
<script>
  jQuery(function($){$('.F').unwrap();});
</script>
like image 45
Dr.Molle Avatar answered Dec 23 '22 05:12

Dr.Molle