How to replace an HTML element with another one using JavaScript?
Replacing an HTML element with another using JavaScript allows for dynamic modification of webpage content without reloading the entire page. Document Object Model (DOM) is a platform and language-neutral interface that is used by programs and scripts to dynamically access the content, style, and structure.
Below are the approaches to replacing an HTML element with another one using JavaScript:
Table of Content
Method 1: Using replaceWith()
This approach utilizes the `replaceWith()` method to replace the selected element with the specified HTML content.
Example: To demonstrate replacing the HTML element with another one using the JavaScript replaceWith() method.
<!DOCTYPE html>
<html>
<head>
<title>Replace Element Example</title>
</head>
<body>
<div id="original">Original Content</div>
<button onclick="replaceElement()">Replace Element</button>
<script>
function replaceElement() {
let newElement = document.createElement('div');
newElement.textContent = 'New Content';
document.getElementById('original').replaceWith(newElement);
}
</script>
</body>
</html>
Output:

Output
Method 2: Using innerHTML Property
This approach uses the `innerHTML` property of the parent element to replace its content with new HTML content.
Example: To demonstrate replacing the HTML element with another one using the JavaScript innerHTML property.
<!DOCTYPE html>
<html>
<head>
<title>Replace Element Example</title>
</head>
<body>
<div id="parent">Original Content</div>
<button onclick="replaceElement()">Replace Element</button>
<script>
function replaceElement() {
document
.getElementById('parent')
.innerHTML = '<div>New Content</div>';
}
</script>
</body>
</html>
Output:

Output
Method 3: Using outerHTML Property
This approach replaces the entire HTML element along with its content using the `outerHTML` property.
Example: To demonstrate replacing the HTML element with another one using the JavaScript outerHTML property.
<!DOCTYPE html>
<html>
<head>
<title>Replace Element Example</title>
</head>
<body>
<div id="original">Original Content</div>
<button onclick="replaceElement()">Replace Element</button>
<script>
function replaceElement() {
let newElement = '<div>New Content</div>';
document.getElementById('original').outerHTML = newElement;
}
</script>
</body>
</html>
Output:

Output