Home > Back-end >  Insert javascript method inside html paragraph
Insert javascript method inside html paragraph

Time:03-29

<!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.

CodePudding user response:

You can use document.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>

CodePudding user response:

Nope, you cannot do that.

What you can do is put a script tag below, which will run without having to click a button.

<!DOCTYPE html>
<html>

<body>

  <h2>My First JavaScript</h2>

  <p id="demo"></p>
  <!-- here I want to put the output of Date() method -->

  <script>
    document.getElementById('demo').innerHTML = Date()
  </script>
</body>

</html>

  • Related