Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating page with "document.write" removes formatting

I've been wondering if there is a way to prevent my functions hiding any current text/formatting.

<body>
<script type="text/javascript">
document.body.style.backgroundColor = "#F5F0EB";
var page = 0
function flip(){
document.write(page);
page++;
}
</script>
<input type=button value="Next" onClick="flip()">
</body>

When I press the button I lose the coloured background and the text appears. Is there a way to make the background stay and the text appear?

like image 520
user2036239 Avatar asked Dec 31 '25 10:12

user2036239


2 Answers

Yes, by not using document.write(). MDN explains it clearly:

Writing to a document that has already loaded without calling document.open() will automatically perform a document.open call.

And about document.open() it says:

If a document exists in the target, this method clears it.

What you should be doing, is manipulate nodes in the DOM. For example, you could change the inner HTML of the body:

document.body.innerHTML += page;

Alternatively, you could create a text node and append it:

var textNode = document.createTextNode(page);
document.body.appendChild(textNode);

In both cases, the current document is not flushed, it is only modified.

like image 83
Mattias Buelens Avatar answered Jan 01 '26 22:01

Mattias Buelens


This is happening because you're writing non-html to a document which should be html. As indicated by others, it may also be clearing your existing html. Instead of using document.write, you may want to append new elements to your document.

You can do that using the document.createElement function and document.appendChild function.

Here's what a quick Google search brought back:

http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/

like image 33
cwharris Avatar answered Jan 02 '26 00:01

cwharris