I am aware how to create a new div or any other HTML element and add it as a child using pure JavaScript.
Am I able to create a new element and add my existing one into it?
For example:
I would like to take the current code below and put it within a brand new div.
// Current elements on page
<div>
<img />
<img />
</div>
<div>
<p>Hello world</p>
</div>
What I want:
// What I want
<div class="my-new-div">
<div>
<img />
<img />
</div>
<div>
<p>Hello world</p>
</div>
</div>
I understand this is easy to do in HTML however. I have to use JavaScript in this scenario to alter a webpage. In this scenario I must add a parent div to avoid changing styles.
You can simply fetch the existing node, create a new one, insert it before the existing node, and finally append the existing node to the new node as child. The browser moves the node when performing the "append" operation, if it is already contained somewhere in the document.
const myDiv = document.getElementById("myDiv");
const myNewDiv = document.createElement("div");
myNewDiv.style.border = "solid 1px";
document.body.insertBefore(myNewDiv, myDiv);
myNewDiv.appendChild(myDiv);
<div id="myDiv">
<p>Hello</p>
<p>Paragraph</p>
</div>
To move one element from one part of the document to another part, you need to associate the element to a new parent. this automatically disassociates the moving element from its old parent.
function newAndMove() {
//Create a new element
let blue = document.createElement('DIV');
blue.classList.add('blue-div');
document.body.appendChild(blue);
//Move existing element inside it
let red = document.getElementById('old-div');
blue.appendChild(red);
}
.red-div {
width: 200px;
height: 200px;
background-color: red;
}
.blue-div {
width: 400px;
height: 400px;
background-color: blue;
position: absolute;
top: 100px;
left: 100pxl
}
<input type="button" value="Get red inside new blue" onClick="newAndMove()">
<div class="red-div" id="old-div"></div>
you can move DOM elements by appending them as a child to the preferred container.