I've been looking on Google and I searched on SO for the answer, but I can't find anything.
The document.write function seems pretty useless because it replaces the previous contents. Does it accept any arguments, or is there a legitimate use for it?
3 Answers 3
Documentation can be found at MDN. It only replaces the content if you call it after the document was parsed.
If it is called during parsing, then the content is just inserted. Quite a few scripts use this, so that you just have to copy and paste them in your HTML where you want to have the output, without any further actions required from your side.
Its usage is not undisputed though, because of what you already mentioned: If you use it at the wrong time, all the content is erased. Furthermore, it is not available in XHTML documents.
But IMO it's the same with many other things: If you are aware of the difficulties/drawbacks and know when to use it, then it's ok to use it.
Comments
One time I was able to pull data from a database structure and paste it into a blank text file with document.write('file.txt'). I had it set to precompile with a parse error but not a domain error. my script looked like:
function func()
{
document.domain == "existing domain"
document.int = String[0]
int.String[0] == 'database, folder, or library')
document.read(int)
document.write('textfile.txt')
}
Then I ran the script in visual studio code against Microsoft edge node, with textile.txt in the same folder as my javascript file.
I did it another way where I had an html file with a form inside an iframe where I equivocated the label in the form to my javascript file and the form and the iframe were inside an where the source link was the domain I was pulling random data from:
function func()
{
array[0] == char charAt['//label1//']
int.array[0] == 'database, folder, or library')
document.read(int)
document.write('textfile.txt')
}
and in the html:
<a href="www.targetlink.com">
<iframe id="label1">
<form label = "label1">
</form>
</iframe>
</a>
Comments
Your argument is correct. It will replace current document's content when the user interacts with the page. Therefor its generally discouraged to use it in modern developments. But it has some great uses such as Document Object Model (DOM) to dynamically update html document.
So, the use of document.write will depend on your usage.
And it accepts arguments.
document.write("Hello!");
This will print Hello where this function called.
Thank you.
httpsor not (and without messing withonloador anything). JS and JS libraries provide good DOM manipulation support, but for some isolated examples like this I wouldn't consider it "useless." Also, sometimes you may just want to overwrite the whole page, you know, to keep users on their toes.