Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is jQuery.html() working when .innerHTML() is failing?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading