Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 431
Wez Avatar asked Aug 31 '11 14:08

Wez


People also ask

How do I append after an element?

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.

How do you append a child to an 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.

What is append child in JavaScript?

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.

Can you append multiple children at once JavaScript?

To append multiple child elements with JavaScript, we can use the append method. Then we write: const listElement = document. querySelector('ul') const listItem = document.


1 Answers

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); 
like image 186
Yoshi Avatar answered Sep 20 '22 16:09

Yoshi