Insert before last child in JavaScript

Description

The following code shows how to insert before last 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><!--   w  ww.  j  a v  a2  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 before last child
var returnedNode = div.insertBefore(p, div.lastChild);
document.writeln(p == div.childNodes[div.childNodes.length-2]); //true
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Insert before last 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...