0

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

5

2 Answers 2

1
  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>
Sign up to request clarification or add additional context in comments.

1 Comment

Adding elements to the body is ok, but your approach won't add h1 to the exact place. It only adds to the end of the body tag.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.