IE 8: remove node keep children

蓝咒 提交于 2019-12-10 16:39:53

问题


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 :)


回答1:


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.




回答2:


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>



回答3:


@Jon's approach, sans iteration:

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

See it in action.


@Dr.Molle's answer should be the accepted one.




回答4:


Next is most 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/



来源:https://stackoverflow.com/questions/12561591/ie-8-remove-node-keep-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!