<!DOCTYPE html>
<html>
<body>
<h2>My First JavaScript</h2>
<p id="demo"><script>Date()</script></p> <!-- here I want to put the output of Date() method -->
</body>
</html>
I know that I can do something like:
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
But I'd like to know if there's a way to do that inside the paragraph directly.
You can usedocument.write
to write content to the HTML directly from JavaScript.
<h2>My First JavaScript</h2> <p id="demo"><script>document.write( Date())</script></p>
NOTE Calling document.write()
after the initial HTML has been parsed will cause the entire HTML to be discarded and a new document will be created . This is only safe to be called while the document is being parsed.
Example of calling document.write after document has been processed
setTimeout(() => { document.write("Written after HTML doc was closed"); }, 5000);
<h1> Hello </h1> <p> I will disappear after document.write is called</p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.