Implement prepend and append with regular JavaScript
The task is to implement prepend() and append() methods using regular JavaScript. We’re going to discuss a few methods. First few methods to know
JavaScript insertBefore() Method: This method inserts a node as a child, just before an existing child, which is specified.
Syntax:
node.insertBefore(newNode, existingNode)
Parameters:
- newNode: This parameter is required. It specifies the node object to insert.
- existingNode: This parameter is required. It specifies the child node to insert the new node before it. If not used, the method will insert the newNode at the end.
Example: This example creates a new <p> element and inserts it as the first child of the <div> element using insertBefore() method.
html
< h1 style = "color:green;" > GeeksforGeeks </ h1 > < p id = "GFG_UP" > </ p > < div id = "parent" > < p class = "child" >child_1</ p > < p class = "child" >child_2</ p > < p class = "child" >child_3</ p > </ div > < button onclick = "gfg_Run()" > Click here </ button > < p id = "GFG_DOWN" > </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = 'Click on button implement prepend method'; el_up.innerHTML = today; function gfg_Run() { var par = document.getElementById("parent"); var child = document.getElementsByClassName("child"); var newEl = document.createElement("p"); newEl.innerHTML = "child_0"; par.insertBefore(newEl, child[0]); el_down.innerHTML = "New element inserted"; } </ script > |
Output:

Implement prepend and append with regular JavaScript
JavaScript appendChild() Method: This method appends a node as the last child of a node.
Syntax:
node.appendChild(Node)
Parameters:
- Node: This parameter is required. It specifies the node object to append.
Example: This example creates a new <p> element and inserts it as the last child of the <div> element using appendChild() method.
html
< h1 style = "color:green;" > GeeksforGeeks </ h1 > < p id = "GFG_UP" > </ p > < div id = "parent" > < p class = "child" >child_1</ p > < p class = "child" >child_2</ p > < p class = "child" >child_3</ p > </ div > < button onclick = "gfg_Run()" > Click here </ button > < p id = "GFG_DOWN" > </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = 'Click on button implement append method'; el_up.innerHTML = today; function gfg_Run() { var par = document.getElementById("parent"); var newEl = document.createElement("p"); newEl.innerHTML = "child_4"; par.appendChild(newEl); el_down.innerHTML = "New element inserted"; } </ script > |
Output:

Implement prepend and append with regular JavaScript
Please Login to comment...