Javascript Append Child AFTER Element

Wez picture Wez · Aug 31, 2011 · Viewed 104k times · Source

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,

parentGuest.appendChild(childGuest);

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

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

Answer

Yoshi picture Yoshi · Aug 31, 2011

You can use:

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

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);