简体   繁体   中英

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). The replaceChild() or replaceWith() methods didn't worked for me.

<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)

this requires that you use the id tag in addition to / instead of class.

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(); but that gets only the FIRST instance of that class. something that's iffy at best. use id for manipulating single divs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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