


How to replace an HTML element with another element using JavaScript?
In this tutorial, we will learn to replace an HTML element with another element using JavaScript.
In some use cases, we need to replace an entire HTML element with a different element. For example, it is very important in form validation. Suppose we get the user's age from a form, and the user enters the wrong age; we can display a validation message by replacing the HTML element. Another use case where we need to replace an HTML element with another HTML element is dynamic content loading, where we have to display web page content based on certain conditions such as location, etc.
Here, we will learn 3 ways to replace HTML elements on web pages.
Use replaceWith() method
The first method uses the replaceWith() method. We need to execute the replaceWith() method by taking the previous element as a reference and passing a new element as a reference. We can create a new element in string format.
grammar
Users can use the replaceWith() Javascript method to replace one HTML element with another HTML element according to the following syntax.
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 HTML that contains the id "oldElement". We call the ReplaceElement() function when the button is clicked. In the replaceElement() function, we create a new "h2" element using the createElement() method. Additionally, we use the textContent attribute to add content to the newly created HTML element. After that, we replace oldElement with newElement using replaceWith() method.
In the output, the user 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>
Use outerHTML attribute
The outerHTML attribute of any element allows us to replace the entire HTML element with another HTML element. We need to assign a new element value to the outerHTML attribute to replace the HTML element.
grammar
Users can use the outerHTML attribute to replace one HTML element with another HTML element according to the following syntax.
document.getElementById(id).outerHTML = newEle;
Example
In the example below, we create a "
" element that contains a "para" id and some text content. In the replaceElement() function, we create a new HTML element in string format and assign its value to the outerHTML attribute of the "
" element.
In the output, the user should click the button to replace the "
" element with the "
" 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>
Copy after login
Example
<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>
In the example below, we create a selection menu with different options. Here we will replace the specific options of the selection menu. Additionally, we create two input fields. One is to get the index number, and the other is to get the user's new option value.
In the replaceOption() function, we get the new input value from the user. After that, we access the option using the index value entered by the user in the input. Next, we replace the option with the new value using the option's outerHTML attribute.
In the output, enter the zero-based index value in the first input field, enter 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>
Use replaceChild() method
The replaceChild() method allows developers to replace the child nodes of a specific HTML element with a new element. Here we can replace the first child element of a specific element to replace itself with the new element.
grammar
Users can use the replaceChild() method to replace one HTML element with another HTML element according to the following syntax.
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 the second parameter.
Example
In the following example, first we create the "h3" element using the createElement() method. After that, we use the createTextNode() method to create the text content. After that, we append the text node to the newly created HTML element using the appendChild() method.
Next, we execute the replaceChild() method by referencing the old element. Additionally, we passed HTMLele as the first parameter (a newly created element), and oldEle.childNodes[0] as the second parameter (the first child element of the old element, representing itself).
In the output, click the button and watch 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 ways to replace one HTML element with another using JavaScript. In the first method, we used the replaceWith() method, which is one of the best and simplest methods. In the second method, we use the outerHTML attribute; in the third method, we use the replaceChild() method, which is generally used to replace child elements.
The above is the detailed content of How to replace an HTML element with another element using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.
