Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Replace Child

To replace an element to the HTML DOM, use the replaceChild() method.


This is a paragraph.

This is another paragraph.



<div id="div1">
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
</div>

// new p node
let newParagraph = document.createElement("p");

// new text node under the new p node
let newText = document.createTextNode("This is new.");

// add the text
newParagraph.appendChild(newText);

// this also works
//newParagraph.innerHTML = "this is new stuff";

// find the parent
let parent = document.getElementById("div1");

// find the node to be replaced
let oldParagraph = document.getElementById("p1");

// replace it.
parent.replaceChild(newParagraph, oldParagraph);