JS AppendChild

The appendChild() method appends a node (element) as the last child of an element.

Syntax

element.appendChild(node)
         or
node.appendChild(node)

Parameters

Parameter Description
node Required.
The node to append.

Return Value

Type Description
Node The appended node.

JS InsertBefore

The insertBefore() method inserts a child node before an existing child.

Syntax

element.insertBefore(new, existing)
             or
node.insertBefore(new, existing)

Parameters

Parameter Description
new Required.
The node (element) to insert.
existing Required.
The node (element) to insert before.
If null, it will be inserted at the end.

Return Value

Type Description
Node The inserted node.

html file

<!DOCTYPE html>
<html>
<head>
    <title>DOM append and insertBefore</title>
    <style>
        h1{
            text-align: center;
            color:#ff0000;
        }
        #test{
            background: #ffff00;
            width: 800px;
            height: 200px;
            padding:10px 10px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <h1>Yahoo Baba : DOM Create Methods</h1>
    <div id="test">
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Consectetur aperiam eos vel consequatur. Delectus voluptas dolorem id exercitationem, ad ipsam consectetur hic ullam provident! Adipisci exercitationem ipsam rerum sunt doloremque magni soluta, delectus maiores, sapiente quasi labore praesentium accusamus earum cum nam saepe qui? Accusamus provident quo perferendis sint sed.</p>
        <h3>yahoo baba</h3>
    </div>
    <script src="js/dom-create.js"></script>
</body>
</html>

dom-create.js


/* Dom Create */
//var newElement = document.createElement("p");

var newElement = document.createElement("h2");

console.log(newElement);

var newText = document.createTextNode("This is just text");

console.log(newText);

/* JavaScript AppendChild*/

newElement.appendChild(newText);

//document.getElementById("test").appendChild(newElement);
    

/* JavaScript  InsertBefore */

var target = document.getElementById("test");
target.insertBefore(newElement,target.childNodes[0])