Computer >> Computer tutorials >  >> Programming >> Javascript

Insert a node as a child before an existing child in JavaScript?


Javascript has provided insertBefore() method to insert a node as a child before another child. If there are 2 lists we can shuffle the elements between them based on our requirement using the method insertBefore().

syntax

node.insertBefore(newnode, existingnode);

Example-1

In the following example, there are two lists and based on our requirement the lists were shuffled using insertBefore() method. To access the multiple elements in a list we can use their indexes.

<html>
<body>
<ul id="List1"> <li>Tesla </li><li>Solarcity </li> </ul>
<ul id="List2"> <li>Google </li> <li>Drupal </li> </ul>
<script>
   var node = document.getElementById("List2").firstChild;
   var list = document.getElementById("List1");
   list.insertBefore(node, list.childNodes[1]);
</script>
</body>
</html>

Output

Tesla
Google
Solarcity

Drupal


Example-2

<html>
<body>
<ul id="List1"> <li>Tesla </li> <li>Solarcity </li> </ul>
<ul id="List2"> <li>Google </li> <li>Drupal </li> </ul>
<script>
   var node = document.getElementById("List2").firstChild;
   var list = document.getElementById("List1");
   list.insertBefore(node, list.childNodes[0]);
</script>
</body>
</html>

Output

Google
Tesla
Solarcity

Drupal