Insert as the new first child in JavaScript

Description

The following code shows how to insert as the new first child.

Example


<!DOCTYPE html>
<html>
<body>
<div id="div1">
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul><!-- ww  w  .  jav  a 2 s.  com-->
</div>
<p id="p1">Hello <b>World!</b></p>


<script type="text/javascript">
var div = document.getElementById("div1");
var p = document.getElementById("p1");

//insert as the new first child
var returnedNode = div.insertBefore(p, div.firstChild);
document.writeln(returnedNode == p); //true
document.writeln(p == div.firstChild); //true
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Insert as the new first child in JavaScript
Home »
  Javascript Tutorial »
    DOM »
      Insert
Javascript Tutorial Insert
Add child to a HTML element in JavaScript
Insert a node before another element using ...
Insert as the new first child in JavaScript
Insert before last child in JavaScript
Insert element before another element in Ja...
Insert to adjacent html with afterbegin in ...
Insert to adjacent html with afterend in Ja...
Insert to adjacent html with beforebegin in...
Insert to adjacent html with beforeend in J...