DOM DOM Element Replacement in Place Using JavaScript
When working with the DOM, there may arise situations where you need to replace an existing element with a different type of element. This can be achieved using the replaceChild() method, as exemplified in the following scenario.
Scenario: Replace an element with a element.
Solution:
<code class="js">// Retrieve the <a> element var myAnchor = document.getElementById("myAnchor"); // Create the <span> element var mySpan = document.createElement("span"); // Set the innerHTML of the <span> element mySpan.innerHTML = "replaced anchor!"; // Replace the <a> element with the <span> element myAnchor.parentNode.replaceChild(mySpan, myAnchor);</code>
This code snippet demonstrates how to effectively replace an element with a element in place using JavaScript, leveraging the replaceChild() method.
The above is the detailed content of How to Replace a DOM Element in Place with a Different Element Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!