The Element class in JavaScript is the basis for creating other elements, including such HTML objects as div, p, etc. Its methods and properties are considered universal because any inherit class will contain them too. One of them is the replaceWith() method, which is often used in HTML pages.

This method allows you to replace an object with another one with a different set of properties. This will save the hierarchy of child objects, but will remove the event and date handlers associated with it. Also, it doesn't save a copy, so after replacing two objects only one will remain.

In general, replaceWith() can be used to replace DOM, HTML elements and jQuery objects. This can be useful for making quick changes to the script or organizing/adjusting its structure for certain conditions.

Syntax

This method has a very simple syntax, according to which the name of the Node or DOM object that should be replaced by the current element must be specified in parentheses:

replaceWith();

In a more complete form, it looks like this:

elementName.replaceWith(targetElement);

Instead of elementName, there must be the element used for replacement, and targetElement should be the name of the element that will be replaced. As parameters, you can use the corresponding name of the DOM element, jQuery object, or HTML page.

Tips

DOM element (in simplified form) can be considered as any part of HTML script that was created and can be modified using JavaScript. This is due to the fact that their interaction (JavaScript with HTML) is based on the DOM model.

Node is a name for highlighting with tags parts of HTML scripts. They can be independent or have a multilevel structure. For example, in the <html> node there can be a <body> node within which there is a <p> node, and so on.

JQuery object is an object created using the jQuery library for JavaScript.

How to use

Let's say, we want to replace an HTML object using the replaceWith() method. To test out  replaceWith() in action we will create a little HTML script. We will create an element with a specific property, and replace it with another element with a different value of the same property. 

It should be noted that the presence or absence of certain properties on elements is not required to use replaceWith(). In our case, we use them to make it easier to track changes made by replaceWith().

Step 1

Let's write the main HTML parts of our script. In the first line, we will declare its type, while with <html> tags, we will indicate its beginning and end. Then, inside these tags, we will create two more areas designated by the <body> and <script> tags. The first will contain the HTML elements visible on the page, and the second will contain the executable part, that is, the functions.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
 </body>
<script></script>
</html>

Step 2

Now we will create the page interface. Let's add a line that will contain the text "Simple text" and have id = "firstID". The text will be the property that we will keep track of, and the id will be used to refer to this line in a future function.

<p id="firstID">"Simple text"</p>

Then we create a button, clicking which will execute the function, which we will call changeDOM. In a typical situation, replaceWith() is performed instantly, so we will activate it only by click.

<button onclick=" changeDOM ()">Click me!!!</button>

Then we'll add both lines to the area between the <body> tags.

Step 3

The code generated at this stage we will place between the <script> tags. First, let's create a variable and make it a part of the document structure:

const firstDOMobj = document.createElement("div");

Then, using the innerHTML method, change its text to "DOM object text". This will be the property that we will monitor to verify that replaceWith() executed correctly.

firstDOMobj.innerHTML = "The first DOM object text";

After that, let's create the changeDOM function we've referenced earlier when we create the button.

function changeDOM () {}

Inside this function, we will add an implementation of the replaceWith() method, which will allow us to execute it on a click on the button. In the first part, we find in the script structure using the value ID (firstID) element which will be replaced. Since we have created a variable for the second element, we just need to write the name of its variable to indicate it as a target.

function changeDOM()  {
  document.getElementById("firstID").replaceWith(firstDOMobj);
}

Step 4

Checking our code with all the necessary parts together.

Result

After executing this script, we get a page with the string (Simple text) and the button below it. After clicking the button, the text above is replaced with the text from the firstDOMobj object. Text change indicates that the replacement was successful. 

Alternatively, you can test the replacement by opening the generated script in a browser. To do this, after loading the page, find the tab with the current page code in Development Tools. After clicking the button, you will see how the object with the <p> tag will be replaced in the document structure with the object with the <div> tag, which was assigned to the firstDOMobj element.

Test yourself

  • Task 1. Correct and supplement the provided code to replace all lines by the NewLineObject element with a button click. You can use the previous example as a guide. 

<!DOCTYPE html>
<html>
 <body>
   <p id="tfirstID">"The first line text"</p>
   <p id="secondID">"The second line text"</p>
   <p id="fourthID">"The third line text"</p>
   <p id="thirdID">"The fourth line text"</p>
   <p id="randomID">"The fifth random line text"</p>
   <button onclick=" ChangeLines ()">Click to change element</button>
 </body>
<script>
 var NewLineObject = document.createElement("div"); NewLineObject.innerHTML =
 "New text";
 </script>
</html>

Since all elements will be replaced with the same value, only one line with the text from newCreatedObj will remain on the page.

  • Task 2. Use the replaceWith() method to fix the quote in a given HTML page.

<!DOCTYPE html>
<html>
<body>
<div class="CitationBox">
<p id="firstID">"To be</p>
<p id="secondID">"Line text 2"</p>
<p id="thirdID">- William Shakespeare</p>
</div>
<script>
const firstINewObject = document.createElement("div");
firstINewObject.innerHTML = "continued...";
const secondNewObject = document.createElement("div");
secondNewObject.innerHTML = ",or not to be, that is the question";
const thirdNewObject = document.createElement("div");
thirdNewObject.innerHTML = "a bee";
</script>
</body>
</html>

Solution:

Add the following line before the </script> tag:

document.getElementById("secondID").replaceWith(secondNewObject);

The page should contain only the following text: "To be, or not to be, that is the question" - William Shakespeare.