How to Move Element in JavaScript
This tutorial will discuss moving one element’s children to another parent using the appendChild()
function in JavaScript.
Move One Element’s Children to Another Parent Using the appendChild()
Function in JavaScript
We can use the appendChild()
function to move one element’s children to another parent in JavaScript. The appendChild()
function adds a child to the given parent. First of all, we have to get the elements in the JavaScript which we can do using the getElementById()
or querySelector()
function. After that, if there is more than one child, we have to use a loop to move each child to the given parent. The loop will add all the children one by one and terminate when no more children are left to add to the parent. For example, let’s create two elements with some children and move one element’s children to another using the appendChild()
function. See the code below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="First Parent Element"></div>
<div id="Second Parent Element">
<span>Hello World</span>
</div>
</body>
<script type="text/javascript">
var FirstParent = document.getElementById('First Parent Element');
var SecondParent = document.getElementById('Second Parent Element');
while (SecondParent.childNodes.length > 0) {
FirstParent.appendChild(SecondParent.childNodes[0]);
}
console.log(FirstParent.childNodes)
</script>
</html>
Output:
NodeList(3) [text, span, text]
In the above code, the first parent element does not have any children and the second parent element has one child. As you can see in the output, the first parent element also has the same child as the second parent element after the loop. We used the console.log()
function to display the children of the first parent element. You can also convert this code into a function, so you don’t have to write the whole code again. For example, let’s flip the above code into a function that will accept two string parameters containing the id of the two parents elements. The function will add the children of the second argument to the parent of the first argument. See the code below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="First Parent Element"></div>
<div id="Second Parent Element">
<span>Hello World</span>
</div>
</body>
<script type="text/javascript">
function MoveChildren(first, second){
var FirstParent = document.getElementById(first);
var SecondParent = document.getElementById(second);
while (SecondParent.childNodes.length > 0) {
FirstParent.appendChild(SecondParent.childNodes[0]);
}
}
MoveChildren('First Parent Element','Second Parent Element');
console.log(document.getElementById('First Parent Element').childNodes)
</script>
</html>
Output:
NodeList(3) [text, span, text]
Now, you can use this function anytime you want to move one element’s children to another element’s parent.