In this example we create a new list element with the text "new text", and select the first unordered list, and its first list element.
let newElement = document.createElement("li");
newElement.innerHTML = "new text";
let parentElement = document.querySelector("ul");
let nextSibling = parentElement.querySelector("li");
When inserting an element, we do it under the parent element, and just before a particular child element of that parent element.
parentElement.insertBefore(newElement, nextSibling);
The new element is inserted under
parentElement
and just beforenextSibling
.
When one wants to insert an element as the last child element of parentElement
, the second argument can be null
.
parentElement.insertBefore(newElement, null);
The new element is inserted under
parentElement
as the last child.
Instead, appendChild()
may be used to simply append the child to the children of the parent node.
parentElement.appendChild(newElement);
The new element is inserted under
parentElement
as the last child.