简体   繁体   English

如何用两个元素替换一个 DOM 元素 - vanilla js

[英]How to replace one DOM element with two elements - vanilla js

I am looking to replace one DOM element (one) with other two elements (two, three).我希望用其他两个元素(两个、三个)替换一个 DOM 元素(一个)。 The replaceChild() or replaceWith() methods didn't worked for me. replaceChild()replaceWith()方法对我不起作用。

<div class="one">
   <div class="two">...</div>
   <div class="three">...</div>
</div>

How can I achieve this?我怎样才能做到这一点?

<div class="two">...</div.
<div class="three">...</div>

this is one way to do it.这是一种方法。 there are likely better ways.可能有更好的方法。 this uses id(which is better for unique elements and using DOM manipulation)这使用 id(这对于唯一元素和使用 DOM 操作更好)

this requires that you use the id tag in addition to / instead of class.这要求您在 / 而不是 class 之外使用 id 标记。

a few key points, this assumes there is a parent node of one.几个关键点,这假设有一个父节点。 (which your code doesn't show). (您的代码未显示)。 it is a requirement for removing nodes, you can't remove a node itself, you can only remove children - so you must specify from what parent you are removing what child.这是删除节点的要求,您不能删除节点本身,只能删除子节点 - 因此您必须指定要从哪个父节点删除哪个子节点。

const one = document.getElementById('one');
const two = document.getElementById('two');
const three= document.getElementById('three');
const onesParent = one.parentNode;
onesParent.removeChild(one);
onesParent.appendChild(two);
onesParent.appendChild(three);

the alternative you using classes is document.getElementByClassName();您使用类的替代方法是 document.getElementByClassName(); but that gets only the FIRST instance of that class.但这只会获得该类的第一个实例。 something that's iffy at best.充其量是不确定的东西。 use id for manipulating single divs.使用 id 来操作单个 div。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM