The appendChild()
method appends a node (element)
as the last child of an element.
element.appendChild(node)
or
node.appendChild(node)
Parameter | Description |
node |
Required. The node to append. |
Type | Description |
Node | The appended node. |
insertBefore()
method inserts a child node before
an existing child.
element.insertBefore(new, existing)
or
node.insertBefore(new, existing)
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.
|
Type | Description |
Node | The inserted node. |
<!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 */
//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])