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 id="Using-the-i-replaceWith-method-i-to-replace-the-HTML-elements-in-JavaScript"> 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 id="Using-the-i-outerHTML-property-i-to-replace-the-HTML-elements-in-JavaScript"> 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 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 id="Using-the-i-outerHTML-property-i-to-replace-the-options-in-the-select-menu"> 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 id="Using-the-i-replaceChild-method-i-to-replace-the-HTML-elements-in-JavaScript"> 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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.