In tutorials I've learnt to use document.write
. Now I understand that by many this is frowned upon. I've tried print()
, but then it literally sends it to the printer.
So what are alternatives I should use, and why shouldn't I use document.write
? Both w3schools and MDN use document.write
.
This is probably the most correct, direct replacement: insertAdjacentHTML.
As a recommended alternative to
document.write
you could use DOM manipulation to directly query and add node elements to the DOM.document.currentScript.insertAdjacentHTML('beforebegin', 'this is the document.write alternative');
https://developer.mozilla.org/en-US/docs/Web/API/Document/currentScript https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
Just dropping a note here to say that, although using
document.write
is highly frowned upon due to performance concerns (synchronous DOM injection and evaluation), there is also no actual 1:1 alternative if you are usingdocument.write
to inject script tags on demand.There are a lot of great ways to avoid having to do this (e.g. script loaders like RequireJS that manage your dependency chains) but they are more invasive and so are best used throughout the site/application.
I'm not sure if this will work exactly, but I thought of
This solved the problem with the error messages for me.
The question depends on what you are actually trying to do.
Usually, instead of doing
document.write
you can usesomeElement.innerHTML
or better,document.createElement
with ansomeElement.appendChild
.You can also consider using a library like jQuery and using the modification functions in there: http://api.jquery.com/category/manipulation/