DOM Manipulating Elements Replacing an element


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

To replace an element, we use replaceChild:

parentElement.replaceChild(newElement, nextSibling);

nextSibling is removed from the DOM. In its place is now newElement.