用其内容替换父元素

Den*_*s G 8 javascript dom

我正在尝试做与这个问题类似/相同的事情: How to remove only the parent element and not its child elements in JavaScript?

<div>
    This is some text here
    <h2>This is more text</h2>
</div>
Run Code Online (Sandbox Code Playgroud)

我想要的只是删除 H2 标签。结果应该是:

<div>
    This is some text here
    This is more text
</div>
Run Code Online (Sandbox Code Playgroud)

假设我已经有了 H2 元素:

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

Dav*_*mas 5

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

var h2 = document.getElementsByTagName('h2')[0],
    textnode = h2.firstChild;

h2.parentNode.insertBefore(textnode,h2.nextSibling);
h2.parentNode.removeChild(h2);?
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示

为了使它稍微更干燥,函数方法可以是:

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);
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示

根据 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);
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示


Gib*_*olt 5

使用现代JS!

const h2 = document.getElementsByTagName('h2')[0];
h2.replaceWith(h2.firstChild);
Run Code Online (Sandbox Code Playgroud)

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

h2.replaceWith(...h2.childNodes); // or h2.children, if you don't want textNodes
Run Code Online (Sandbox Code Playgroud)

developer.mozilla.org

我可以使用吗- 2020 年 4 月 94%