3

I am trying to do some proves with JavaScript but I see a behaviour that I consider that it do not have to be like this. Here is my code:

Code:

<!DOCTYPE html>
   <head>
       <meta charset = "utf-8"/>
       <title> Exercise prompt </title>
       <script type = "text/javascript">
          function disp_prompt()
          {
             var name = prompt("Please enter your name", "");
             
             if(name != null && name != "")
             {
                document.write("Hi " + name + " How are you?");
             }      
          }
       </script>
   </head>
   <body>
       <input type = "button" onclick = "disp_prompt()" value = "Show a prompt box." />
   </body>
</html>

Expected result:

When I click on the button, the prompt appears and when I click the button "Accept", the sentence on the function document.write have to be under the button.


Result:

When the prompt box it is displayed and I press the button "Accept", the button dissappear and it is only shown the sentence on the function document.write.


I can see on w3schools the following sentence:

Write some text directly to the HTML document

but I also could see another statement:

Using document.write() after an HTML document is fully loaded, will delete all existing HTML.

So I cannot understand the real purpose of document.write. If you want to write some text on your HTML... Why it has to remove the rest of the elements?

Is there a method to avoid that and to keep the rest of the elements on the HTML?

Thanks in advance!

Community
  • 1
  • 1
Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
  • 2
    The second answer in a somewhat similar question I posted a while back might have some good answers to it: http://stackoverflow.com/questions/12574098/is-document-write-actually-deprecated – Stephen Sep 28 '15 at 23:41
  • use DOM methods/ _innerHTML_ to update your content. _document.write()_ , outside of a few edge cases, should be avoided. it can be used to sync-load scripts, inject ads, or affect the way the page renders by injecting dynamic content. – dandavis Sep 28 '15 at 23:45
  • 1
    How should the browser know that the content should appear below the button? – Felix Kling Sep 28 '15 at 23:49
  • 2
    Avoid w3schools, your first recourse should be to relevant specifications. For examples and further explanation, use [*MDN*](https://developer.mozilla.org/en-US/docs/Web/API/Document/write). – RobG Sep 28 '15 at 23:53
  • 1
    "real" purpose could be writing the entire page clientside via javascript using document.open(), document.write() and document.close(). – GrafiCode Sep 28 '15 at 23:56
  • @FelixKling I though that it was going to write after the rest of the elements. For example, in the code given by `Amit` it doesn't dissapear. – Francisco Romero Sep 29 '15 at 10:00

2 Answers2

3

The purpose of document.write() is to insert some dynamic / calculated content to the page exactly where the script is placed. For example (although a contrived one...):

<html>
<body>
  hello, the date is <script>document.write(new Date())</script>
</body>
</html>

A more flexible approach that lets you modify the page content after it's fully loaded is to use a dedicated element to host you content, and change it's innerHTML

function clicked() {
  document.getElementById('dynamic').innerHTML = 'It was clicked!';
}
<span onclick="clicked()">Click Me</span><br>
<span id="dynamic"></span>

Other then that, there are numerous libraries that help make that simpler, most notably, jQuery.

Amit
  • 45,440
  • 9
  • 78
  • 110
  • Yes but in your code the first element it is not overwrited by the `document.write`. In my case, the button dissapear because it is overwritten by the sentence that I put on the `document.write`. – Francisco Romero Sep 29 '15 at 09:56
  • because as I explained `document.write()` inserts content exactly where it's placed. you can think of it as if you take out the entire script block and replace it with what you pass to the function. in your case the entire document is replaced since once it's closed (fully loaded), calling `document.write()` will overwrite it completely as you saw yourself. – Amit Sep 29 '15 at 10:08
  • Then, the button it is replaced because the function in which I use it is called when I use the button, right? – Francisco Romero Sep 29 '15 at 10:52
  • Not at all, it is replaced because whatever existed before `document.write()` is gone. If you had 3 buttons, a table an a million images they will all be gone. Even if the trigger to do anything is not a button click but any other event (mouse move, input change, timeout... anything). – Amit Sep 29 '15 at 11:00
  • But I am getting confused with your first snippet of code. Why when you use `document.write` the `hello, the date is` statement does not dissapear? I am sorry if I missunderstood you. – Francisco Romero Sep 29 '15 at 11:10
  • 1
    because the `document.write()` is being processed **before** the document is loaded and closed. it happens synchronously and in place, exactly where that code lies. as opposed, in your code the call is processed **after** the document is closed, inside an event handler. – Amit Sep 29 '15 at 11:12
-1
<html>
    <head>
        <meta charset = "utf-8"/>
        <title> Exercise prompt </title>
        <script type = "text/javascript">
            function disp_prompt()
            {
                var name = prompt("Please enter your name", "");
                if(name != null && name != "")
                {
                    document.getElementById("demo").innerHTML ="Hi " + name + " How are you?";
                }
            }
        </script>
    </head>
    <body>
        <button type = "button"  onclick = "disp_prompt()" >
            Show a prompt box.
        </button>
        <p id="demo">
        </p>
    </body>
</html>
  • 3
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 28 '22 at 09:47