It seems that experienced web developers frown upon using document.write() in JavaScript when writing dynamic HTML.
Why is this? and what is the correct way?
It seems that experienced web developers frown upon using document.write() in JavaScript when writing dynamic HTML.
Why is this? and what is the correct way?
element.InnerHtml= allmycontent: will re-write everything inside the element. You must use a variable let allmycontent="this is what I want to print inside this element"to store the whole content you want inside this element. If not each time you will call this function, the content of your element will be erased and replace with the last call you made of it.
document.write(): can be use several times, each time the content will be printed where the call is made on the page.
But be aware: document.write() method is only useful for inserting content at page creation . So use it for not repeating when having a lot of data to write like a catalogue of products or images.
Here a simple example: all your li for your aside menu are stored in an array "tab", you can create a js script with the script tag directly into the html page and then use the write method in an iterative function where you want to insert those li on the page.
<script type="text/javascript">
document.write("<ul>");
for (var i=0; i<=tab.length; i++){
document.write(tab[i]);
}document.write("</ul>");
</script>`
This works because Js is interpreted in a linear way during the loading. So make sure your script is at the right place in your html page.You can also use an external Js file, but then again you must declare it at the place where you want it to be interpreted.
For this reason, document.write cannot be called for writing something on your page as a result of a "user interaction" (like click or hover), because then the DOM has been created and write method will, like said above, write a new page (purge the actual execution stack and start a new stack and a new DOM tree). In this case use:
element.innerHTML=("Myfullcontent");
To learn more about document's methods: open your console: document;
then open: __proto__: HTMLDocumentPrototype
You'll see the function property "write" in the document object.
You can also use document.writeln which add a new line at each statement.
To learn more about a function/method, just write its name into the console with no parenthesis: document.write;
The console will return a description instead of calling it.