Muhammad Bin Salman
Muhammad Bin Salman

Reputation: 19

How to add HTML in between script tag

For example this is my code

<html>
  <head><title>Document</title></head>
  <body>
    <script>
      let input0 = parseInt(prompt("Write a number"))
      let input1 = parseInt(prompt("Write an other number"))
      if (input0 === input1){
        //Here I want to print some text on webpage intead of
        //using document.write or console.log
      }
    </script>
  </body>
</html>

now i want to print a text in h1 tag but if the condition mets, how can i perform this task

Upvotes: 0

Views: 802

Answers (2)

Yevhenii Shlapak
Yevhenii Shlapak

Reputation: 786

Actually, this is the wrong approach. You should add a script tag at the end of the body tag. And you have to add a container, where you want to add your H1 tag.

<html>
  <head>
    <title>Document</title>
  </head>
  <body>
    <div class="h1-container"></div>
    <script>
      let input0 = parseInt(prompt("Write a number"));
      let input1 = parseInt(prompt("Write an other number"));
      if (input0 === input1) {
        //Here I want to print some text on webpage intead of
        //using document.write or console.log
        const container = document.querySelector(".h1-container");
        const h1 = document.createElement("H1");
        const text = document.createTextNode("Hi there!");
        h1.append(text);
        container.append(h1);
      }
    </script>
  </body>
</html>

Upvotes: 0

Jane
Jane

Reputation: 334

  1. use createElement("H1") to create a h1 tag
  2. use createTextNode("") to create text content and append it to h1 tag
  3. append h1 tag to document.body

Here is the code:

<html>
  <head>
    <title>Document</title>
  </head>
  <body>
    <script>
      let input0 = parseInt(prompt("Write a number"));
      let input1 = parseInt(prompt("Write an other number"));
      if (input0 === input1) {
        //Here I want to print some text on webpage intead of
        //using document.write or console.log
        var h1 = document.createElement("H1");
        var text = document.createTextNode("Hi there!");
        h1.append(text);
        document.body.append(h1);
      }
    </script>
  </body>
</html>

Upvotes: 1

Related Questions