javascript - 即 8 : remove node keep children

标签 javascript jquery dom internet-explorer-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);
}

示例输入节点:

<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 会忽略/删除嵌套的子项。

如果有任何帮助,我将不胜感激:)

最佳答案

这样做应该很容易:

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

See it in action .

关于javascript - 即 8 : remove node keep children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12561591/

相关文章:

javascript - 类型错误 : Cannot read property "range" from undefined.(第 2 行,文件 "Server")

javascript - 高度固定为 100% 的水平滚动

jquery - href 与脚本化页面转换和按钮突出显示

javascript - HTML 5 Canvas - 文本到多边形

javascript - 具有命名 View 的 UI 路由器查询参数

javascript - 从日期和时间字符串中删除时间

javascript - td 元素上的 OnClick 函数返回第一列值和标题值

javascript - document.getElementById() 如何搜索 DOM 树?

javascript - 每个类(class)运行一次,但组运行一次

javascript - 获取表单元素作为关联数组?