I need to change a div parent programmatically. For example
<body>
<div id="div_a">
<div id="child"></div>
</div>
<div id="div_b">
</div>
</body>
I wonder if it is possible to change the div with id="child" parent to a div with id="div_b" ?
I have search, but nowhere close. But in case there is a similar question, please let me know.
Thank you
I need to change a div parent programmatically. For example
<body>
<div id="div_a">
<div id="child"></div>
</div>
<div id="div_b">
</div>
</body>
I wonder if it is possible to change the div with id="child" parent to a div with id="div_b" ?
I have search, but nowhere close. But in case there is a similar question, please let me know.
Thank you
Share Improve this question asked Apr 1, 2020 at 1:50 LynLyn 5074 silver badges15 bronze badges 1-
please be more specific, tou want to transform
<div id="child
to a<div id="div_b
and move it outside<div id="div_a
? – Mister Jojo Commented Apr 1, 2020 at 2:11
4 Answers
Reset to default 4You can simply use appendChild
and pass the node as the parameter. A node cannot be in two places at once, so it will move it to the proper location.
let child = document.querySelector("#child");
let parent = document.querySelector("#div_b");
parent.appendChild(child);
<div id="div_a">
<div id="child"></div>
</div>
<div id="div_b">
</div>
In pure JS, you can use document.querySelector
(or document.getElementById
) and Node.appendChild
to append the #child
div to the #div_b
div. Since a node cannot exist in more than one place, this automatically also removes it from #div_a
:
document.querySelector('#div_b').appendChild(document.querySelector('#child'));
// or document.getElementById('div_b').appendChild(document.getElementById('child'));
<body>
<div id="div_a">
Div A!
<div id="child">I am a child of Div A</div>
</div>
<hr/>
<div id="div_b">
Div B!
</div>
</body>
You need to add the element to the new parent, then remove it from the old one. If you can use JQuery you can do it easily with
jQuery("#child").detach().appendTo('#div_b')
with JavaScript
var tmp = document.getElementById('child');
document.getElementById('div_b').appendChild(tmp.cloneNode(true));
tmp.remove();
Depending on the your application you may want to use querySelector or querySelectorAll to get the div with id="child". Then using [insert element var].classlist() you can .remove('child') and then .add('div_b').