Hoseong Jeon
Hoseong Jeon

Reputation: 1350

Is there any bug with document.write()?

I had my code something like this:

window.onload = function() {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("value", "");
    document.body.appendChild(x);
}

And I wanted to write something more, I added a new line.

Like this:

window.onload = function() {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("value", "");
    document.body.appendChild(x);
    document.write("<br>");
}

And then, suddenly, my input tag disappeared.

So, I wrote 'AAA'to check whether the <br> code was added or not.

Like this:

window.onload = function() {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("value", "");
    document.body.appendChild(x);

    document.write("<br>");
    document.write("AAA")
}

There's a new line, and AAA.

So, I think there's an bug or something with document.write().

Is there any bug?

Or did I write something wrong?

My purpose is to add a new line.

I want to make my code run properly.

Is there any way to solve this problem?

Upvotes: 0

Views: 79

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370759

The problem is that, if the page has already loaded, document.write will replace the entire page with the new HTML string. If you removed your window.onload handler and simply had that snippet run as soon as the browser comes to the <script> tag, both the <input> and <br> would be inserted into the document as expected:

<script language="javascript">
  var x = document.createElement("INPUT");
  x.setAttribute("type", "text");
  x.setAttribute("value", "");
  document.body.appendChild(x);
  document.write("<br>");
</script>

Generally, the solution is to not use document.write - its behavior can be confusing, and it provides nothing that can't be accomplished just as easily with methods such as appendChild and insertAdjacentHTML, for example:

document.body.appendChild(document.createElement('br'));

or

document.body.insertAdjacentHTML('beforeend', '<br>');

Upvotes: 3

Related Questions