let’s say I have
var myCanvas = document.createElement('canvas');
and I do
myCanvas.setAttribute("id", "my-canvas");
document.body.appendChild(myCanvas);
Afterwords I make change to myCanvas and want to replace the html-canvas with my updated DOM canvas. The following works:
document.getElementById("my-canvas").innerHTML = myCanvas;
but the html (via inspector) looks like
<canvas id="my-canvas">[object HTMLCanvasElement]</canvas>
When it should look like
<canvas id="my-canvas"></canvas>
How can I update the element and not use innerHTML?
You don’t have to update
myCanvasif it is still the same node. When you create a node and you append it do the DOM then the DOM node is live. It means that all changes on themyCanvaswill be immediately reflected in the page.replaceChild()
In case you want to replace a node with different node you can use
.replaceChild()on the parent element of the node you want to replace.Example:
Where
parentis the parent element ofelement.innerHTML
In your question you are using
innerHTML. If you want just to replace a content of one element by a content of another element, then useinnerHTMLon both of them.Example: