2019 Update:
child.replaceWith(newElement);
https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith
In the specific case of this question, I would recommend using replaceWith
with a clone of the node OP wishes to swap in. This could look like:
const main = document.getElementById('main');
const original = document.getElementByid('operation1');
const clone = original.cloneNode(true);
main.replaceWith(clone);
This would probably present an issue the next time you go to swap the element, but you could adapt this solution to fit your needs.
Original Post:
The best way to do this would be to not use innerHTML
, due to possible unforseen side effects. The best way to do this would be to:
- First clone the desired div
- Second empty the main div
- Third append the clone into the main div
This would look very much like the following:
function swapContent (id) {
const main = document.getElementById('main');
const div = document.getElementById(id);
const clone = div.cloneNode(true);
while (main.firstChild) main.firstChild.remove();
main.appendChild(clone);
}
Do not allow yourself to fall into the many pitfalls of using innerHTML
; cloning a node has a much better chance of doing exactly what you're expecting it to do.
Some of the problems with innerHTML
are that it only copies the HTML, and not the DOM, meaning that you do not copy over anything on that DOM node, like event listeners, properties (like value), etc. Cloning a node (and its children) clone that DOM node, which clones its properties respectively.
It is also considered poor practice (by most) to use inline event handlers on your HTML; separation of concerns!