appendChild() inserts the element as child to end of selected node.
insertBefore() method inserts a node before existing node and as a child of parent node.
Let’s see it in action starting with below markup.
We are going to insert
🍬 Candy before second list element i.e.
🍩 Doughnut (between first and second element). The updated list would move the
🍩 Doughnut to third place.
getElementById() and pass
id of parent node i.e.
querySelectorAll() and pass selector
#menu li as argument which would return all list elements. Then we use the index
 to select the second element.
First, create a list element
Next, we create a text node containing text
🍬 Candy and append it to newly created list element i.e.
Finally, we can add the newly created list element right before the second element as follows
We are going to wrap Step 3 and Step 4 in function
insertCookies() and call it on a button click. This will allow us to click the button on UI and insert element dynamically before second list item.
In this step we are going to add a button element that will call function
insertCookies() on click. We are going to place button just before the
<div id="parent"> element.
When you click on button “Insert Cookie Before Doughnut” a new cookie gets inserted before second list item. If you keep clicking the button again and again, a new cookie gets inserted at second place.