How to replace an HTML element with another one using JavaScript?


In this tutorial, we will learn to replace an HTML element with another one using JavaScript.

In some use cases, we require to replace a whole HTML element with a different one. For example, it is very important in the form validation. Suppose we are taking the user’s age from the form, and the user enters the wrong age; we can show the validation message by replacing the HTML element. Another use case where we require to replace an HTML element with another one is dynamic content loading, in which we must show the web page content based on certain criteria such as location, etc.

Here, we will learn 3 approaches to replacing HTML elements of the web page.

Using the replaceWith() method

The first approach uses the replaceWith() method. We require to execute the replaceWith() method by talking the previous element as a reference and by passing a new element as a reference. We can create a new element in the string format.

Syntax

Users can follow the syntax below to use the replaceWith() Javascript method to replace one HTML element with another.

oldElement.replaceWith(newElement);

In the above syntax, oldElement is a replaceable element, and newElement is a replaced element.

Example

In the example below, we have a div element in the HTML containing the ‘oldElement’ id. We call the replaceElement() function on the button click. In the replaceElement() function, we use the createElement() method to create a new ‘h2’ element. Also, we use the textContent property to add the content to the newly created HTML elements. After that, we use the replaceWith() method to replace the oldElement with a newElement.

In the output, users can click the button and see the changes on the web page.

<html>
<body>
   <h3> Using the <i> replaceWith() method </i> to replace the HTML elements in JavaScript </h3>
   <div id = "oldElement"> This div is the old element. </div>
   <button onclick = "replaceElement()"> Replace Element </button>
   <script>
      function replaceElement() {
         var newElement = document.createElement('h2');
         newElement.textContent = 'This element is the new element.';
         var oldElement = document.getElementById('oldElement');
         oldElement.replaceWith(newElement);
     }
   </script>
</html>

Using the outerHTML property

The outerHTML property of any element allows us to replace the whole HTML element with another HTML element. We require to assign a new element value to the outerHTML property to replace the HTML element.

Syntax

Users can follow the syntax below to use the outerHTML property to replace one HTML element with another one.

document.getElementById(id).outerHTML = newEle;

Example

In the example below, we created the ‘<p>’ element containing the ‘para’ id and some text content. In the replaceElement() function, we create a new HTML element in the string format and assign its value to the outerHTML property of the ‘<p>’ element.

In the output, users should click the button to replace the ‘<p>’ element with the ‘<h2>’ HTML element.

<html>
<body>
   <h3> Using the <i> outerHTML property </i> to replace the HTML elements in JavaScript </h3>
   <p id = "para"> Welcome to the TutorialsPoint! </p>
   <button onclick = "replaceElement()"> Replace Element </button>
   <script>
      function replaceElement() {
         let newEle = '<h2> You clicked the button to replace the element. <h2>';
         document.getElementById('para').outerHTML = newEle;
      }
   </script>
</html>

Example

In the example below, we created the select menu containing the different options. Here, we will replace the particular option for the select menu. Also, we created two input fields. One is to take the index number, and another is to take the user's new value for the option.

In the replaceOption() function, we get the new input value from the users. After that, we access the option using the index value which users have entered in the input. Next, we use the outerHTML property of the option to replace the option with new values.

In the output, enter the zero-based index value in the first input field and the new option value in the second input field, and click the button to replace the option.

<html>
<body>
   <h3> Using the <i> outerHTML property </i> to replace the options in the select menu </h3>
   <label for = "indexInput"> Index: </label>
   <input type = "number" id = "indexInput">  <br>  <br>
   <label for = "valueInput"> New Value: </label>
   <input type = "text" id = "valueInput">   <br>  <br>
   <select id = "demo">
      <option value = "1"> One </option>
      <option value = "2"> Two </option>
      <option value = "3" selected> Three </option>
      <option value = "4"> Four </option>
      <option value = "5"> Five </option>
      <option value = "6"> Six </option>
   </select>
   <button onclick = "replaceOption()"> Replace Option </button>
   <script>
      function replaceOption() {
          // get user input
          var index = parseInt(document.getElementById('indexInput').value);
          var newValue = document.getElementById('valueInput').value;
          var list = document.getElementById('demo');
          // get the option to replace
          var option = list.options[index];
          // replace the option
          option.outerHTML = '<option value="' + newValue + '">' + newValue + '</option>';
      }
   </script>
</html>

Using the replaceChild() method

The replaceChild() method allows developers to replace the child nodes of the particular HTML element with a new one. Here, we can replace the first child of the particular element to replace itself with a new element.

Syntax

Users can follow the syntax below to use the replaceChild() method to replace one HTML element with another one.

oldEle.replaceChild(HTMLele, oldEle.childNodes[0]);

In the above syntax, we need to pass the new element as the first parameter of the replaceChild() method and the old element as a second parameter.

Example

In the example below, first we created the ‘h3’ element using the createElement() method. After that, we used the createTextNode() method to create text content. After that, we used the appendChild() method to append the text node to the newly created HTML element.

Next, we execute the replaceChild() method by referencing the old element. Also, we passed the HTMLele as a first parameter, a newly created element, and oldEle.childNodes[0] as a second parameter, the first child of the old element, representing itself.

In the output, click the button and observe the changes on the web page.

<html>
<body>
   <h3> Using the <i> replaceChild() method </i> to replace the HTML elements in JavaScript </h3>
   <p id = "para"> Welcome to the TutorialsPoint! </p>
   <button onclick = "replaceElement()"> Replace Element </button>
   <script>
      function replaceElement() {
         // create a new element
         var HTMLele = document.createElement("h3");
         // create a new text node
         var txt = document.createTextNode("This is a content of new element!");
         // use appendChild() to add a text node to the element
         HTMLele.appendChild(txt);
         var oldEle = document.getElementById("para");
         // using replaceChild() to replace the old element with a new element
         oldEle.replaceChild(HTMLele, oldEle.childNodes[0]);
       }
   </script>
</html>

We learned three different approaches to replacing one HTML element with another one using JavaScript. In the first approach, we used the replaceWith() method, one of the best and easy approaches. In the second approach, we used the outerHTML property; In the third approach, we used the replaceChild() method, which is generally used to replace child elements.

Updated on: 17-May-2023

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements