I have just started learning javascript from w3school and I have found out that "You can only use document.write in the HTML output. If you use it after the document has loaded, the whole document will be overwritten." so I have tried to write following code to check the validity:
<html>
<head>
<title>ashish javascript learning</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<p> sample html with javascript </p>
<script>
document.write("<h1>this is heading</h1>");
document.write("<p>this is sample para</p>");
</script>
<script>
if(document.readyState === "complete"){
loaded();
}
function loaded(){
document.write("<p>loading content after the document has been loaded");
}
</script>
</body>
</html>
Code is still showing the old value and is not overwriting the content of the web page. Could you suggest me what am I doing wrongly.
At the time you're testing document.readyState === "complete"
, the document's readyState isn't "complete", it "loading", so nothing happens, and loaded
is never called.
You can listen for the readyState to change, and then check to see if it is "complete" (or listen to window.onload
which is easier):
document.addEventListener('readystatechange', e => {
if(document.readyState === "complete"){
loaded();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With