I have some code that produces a <canvas> element, that I am attempting to update from jQuery to modern vanilla JS.
Per most documentation on the internet, including this question on StackOverflow I am attempting to use element.innerHTML to replace jQuery’s html() method.
However this using element.innerHTML fails, whereas jQuery html() works:
// Fails
// element.innerHTML = qrCodeCanvas.outerHTML;
// Works
$(element).html(qrCodeCanvas);
See this JSFiddle
How can I replace the .html() with vanilla JS?
>Solution :
The jQuery .html() function involves a whole lot of work besides updating the DOM via .innerHTML. In this case, you’ve already got a DOM element (the <canvas>) so .innerHTML makes no sense. The jQuery code detects that you passed a DOM element (and not HTML text as a string), so it appends it to the DOM for you.
Using .outerHTML will turn your <canvas> back into a string, but you don’t want that because that other code has already drawn onto the canvas; getting the HTML will lose that.
The browser API equivalent of .innerHTML in this case would be .appendChild().