Wezly Wezly - 1 year ago 95
Javascript Question

Javascript Append Child AFTER Element

I would like to append an li element after another li inside a ul element using javascript, This is the code I have so far..

var parentGuest = document.getElementById("one");
var childGuest = document.createElement("li");
childGuest.id = "two";

I am familiar with appendChild,


However this appends the new element inside the other, and not after. How can I append the new element after the existing one? Thanks.

<li id="one"><!-- where the new li is being put --></li>
<!-- where I want the new li -->

Answer Source

You can use:

if (parentGuest.nextSibling) {
  parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
else {

But as Pavel pointed out, the referenceElement can be null/undefined, and if so, insertBefore behaves just like appendChild. So the following is equivalent to the above:

parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download