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>
First, select the ul element by its id ( menu ) using the getElementById() method. Second, create a new list item using the createElement() method. Third, use the insertAfter () method to insert a list item element after the last list item element.
To create a new element to be inserted at the end of a parent node, first use createElement to create it and then appendChild() for the newly-created element. The appendChild() method also works on existing child nodes, using which you can move them to new positions within the document.
The appendChild() is a method of the Node interface. The appendChild() method allows you to add a node to the end of the list of child nodes of a specified parent node.
To append multiple child elements with JavaScript, we can use the append method. Then we write: const listElement = document. querySelector('ul') const listItem = document.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With