Wezly Wezly - 3 months ago 18
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 -->


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