如何将两个 HTMLElements 合并为一个 Javascript

How to append two HTMLElements into one Javascript

所以,我使用了两个 HTMLElements:

var el1 = document.getElementById('div1')
var el2 = document.getElementById('div2');

我想要做的是合并插入到两个容器中的这 2 个元素,如下所示:

<container-x1>
    <container-x2>
        <div id="div1">test1</div>
    </container-x2>
</container-x1>

<container-y1>
    <container-y2>
        <div id="div2">test2</div>
    </container-y2>
</container-y1>

此后我的目标是完全删除容器 y1 并将测试 1 和测试 2 合并到同一个容器中,如下所示:

<container-x1>
    <container-x2>
        <div id="div2">test1  test2</div>
    </container-x2>
</container-x1>

有什么帮助吗?提前致谢

你可以试试这个:

const el1 = document.getElementById('div1');
const el2 = document.getElementById('div2');

el2.innerHTML = el1.innerHTML + ' ' + el2.innerHTML;

el1.replaceWith(el2);

document.getElementsByTagName('container-y1')[0].remove();
<container-x1>
    <container-x2>
        <div id="div1">test1</div>
    </container-x2>
</container-x1>

<container-y1>
    <container-y2>
        <div id="div2">test2</div>
    </container-y2>
</container-y1>