将父元素替换为其内容

Replace parent element with its contents

本文关键字:替换 元素      更新时间:2023-09-26

我正在尝试做与这个问题类似/相同的事情:如何在JavaScript中只删除父元素而不删除其子元素?

<div>
    This is some text here
    <h2>This is more text</h2>
</div>

我只想去掉H2标签。结果应该是:

<div>
    This is some text here
    This is more text
</div>

假设我已经有H2元素:

if (parentElement.nodeName.toLowerCase() == "h2") {
    //now what? I basically want to this: $.replaceWith(parentElement.innerText)
    //just without jQuery
}

使用现代JS

const h2 = document.querySelector('h2');
h2.replaceWith(h2.firstChild);

要替换为所有子项,请使用:

h2.replaceWith(...h2.childNodes); // or h2.children, if you don't want textNodes

developer.mozilla.org

我可以使用-96%Oct'22

假设变量h2准确地引用了您想要操作的h2元素,我的第一个想法是:

var h2 = document.getElementsByTagName('h2')[0],
    textnode = h2.firstChild;
h2.parentNode.insertBefore(textnode,h2.nextSibling);
h2.parentNode.removeChild(h2);​

JS Fiddle演示。

为了使其更干燥,一种函数方法可以是:

function unwrapH2(el) {
    if (!el) {
        return false;
    }
    else {
        var textnode = el.firstChild,
            elParent = el.parentNode;
        elParent.insertBefore(textnode, h2.nextSibling);
        elParent.removeChild(h2);
    }
}
var h2 = document.getElementsByTagName('h2')[0];
unwrapH2(h2);

JS Fiddle演示。

根据Felix Kling的评论(如下)对上述内容进行了调整,并使用了replaceChild():

function unwrapH2(el) {
    if (!el) {
        return false;
    }
    else {
        var textnode = el.firstChild,
            elParent = el.parentNode;
        elParent.replaceChild(textnode,el);
    }
}
var h2 = document.getElementsByTagName('h2')[0];
unwrapH2(h2);

JS Fiddle演示。

首先,开始使用jQuery。它让你的生活更轻松。

在jQuery中,执行以下操作:

var h2html = $('div h2').html();
$('div h2').remove();
$('div').append(h2html);

编辑:

以上仅适用于1个div和1个h2元素,这是div中的最后一个元素。这只是一个快速示例。以下是让你的生活更加轻松的代码:

$('div h2').each(function (x, y) {
    $(this).replaceWith($(this).html());
});​