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,
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>
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);
You need to append the new element to existing element's parent before element's next sibling. Like:
var parentGuest = document.getElementById("one");
var childGuest = document.createElement("li");
childGuest.id = "two";
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
Or if you want just append it, then:
var parentGuest = document.getElementById("one");
var childGuest = document.createElement("li");
childGuest.id = "two";
parentGuest.parentNode.appendChild(childGuest);
If you are looking for a plain JS solution, then you just use insertBefore()
against nextSibling
.
Something like:
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
Note that default value of nextSibling
is null
, so, you don't need to do anything special for that.
Update: You don't even need the if
checking presence of parentGuest.nextSibling
like the currently accepted answer does, because if there's no next sibling, it will return null
, and passing null
to the 2nd argument of insertBefore()
means: append at the end.
Reference:
- nextSibling
- insertBefore
.
IF you are using jQuery (ignore otherwise, I have stated plain JS answer above), you can leverage the convenient after()
method:
$("#one").after("<li id='two'>");
Reference:
- jQuery after()
This suffices :
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling || null);
since if the refnode
(second parameter) is null, a regular appendChild is performed. see here : http://reference.sitepoint.com/javascript/Node/insertBefore
Actually I doubt that the || null
is required, try it and see.