Refreshing the page with "document.write" removes formatting

I was wondering if there is a way to prevent my functions from hiding the 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 click the button, I lose the colored background and the text appears. Is there a way to make the background stay and text appear?

+3


source to share


4 answers


Yes, not using document.write()

. MDN explains it clearly :

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

And about document.open()

he says :

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

What you have to do is manipulate the nodes in the DOM. For example, you can change the inner HTML of the body:



document.body.innerHTML += page;

      

Alternatively, you can create a text node and add it:

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

      

In both cases, the current document is not reset, it only changes.

+3


source


This is because you are writing a non-html document that must be html. As pointed out by others, it can also clear your existing html. Instead of using it, document.write

you can add new elements to your document.

You can do this with the document.createElement

and function document.appendChild

.



Here's what a quick Google search returned:

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

+1


source


You are writing a page into a document that is rewritten throughout the HTML. Instead, write out the content to a DIV.

This should also fix the background color issue.

Here's a JS Fiddle with an example.

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

      

Good luck.

0


source


As Matthias Buelens explained, document.write

calls a method open

that clears the DOM, simply because the method document.close

is automatically called after loading . There are, of course, several alternatives that you can use.
For example, use an attribute on an innerHTML

element body

.
Use document.createElement

and is document.body.appendChild

also an option

But it might be worth considering that both methods have their drawbacks: using innerHTML

it allows you to inject bad formatted markup into the DOM and can leave you vulnerable to XSS attacks.
Usage is document.createElement

slower (usually) and often requires more code, which in turn makes your script (s) less convenient.

You can use something like this:

var flip = (function(tempDiv)
{//create a div once
    var page = 0,
    targetDiv = document.getElementById('contentgoeshere');//closure variables
    //page is now no longer an evil global, and the target element into which
    //we will inject new data is referenced, so we don't have to scan the DOM
    //on each function call
    return function(overridePage)//optional argument, just in case
    {//actual flip function is returned here
        overridePage = overridePage || page++;//new content
        tempDiv.innerHTML = overridePage;//render in div that isn't part of the DOM
        //any number of checks can go here, like:
        if (tempDiv.getElementsByTagName('script').length > 0)
        {
            alert('Naughty client, trying to inject your own scripts to my site');
            return;
        }
        targetDiv.innerHTML = tempDiv.innerHTML;
        //or, depending on your needs:
        targetDiv.innerHTML = tempDiv.innerText;//or the other way 'round
    };
}(document.createElement('div')));

      

A couple of notes: now, as now, this function will not work because the DOM must be fully loaded to close. The quick fix would be as follows:

var flip;//undefined
window.onload = function()
{
    flip = (function(tempDiv)
    {
        var page = 0,
        targetDiv = document.getElementById('contentgoeshere');
        return function(e)
        {
            tempDiv.innerHTML = e instanceof Event ? page++ : (e || page++);//ternary + logical or
            //your [optional] checks here
            targetDiv.innerHTML = tempDiv.innerHTML;
            if (e instanceof Event)
            {//this part is optional, but look it up if you want to: it good stuff
                e.returnValue = false;
                e.cancelBubble = true;
                if (e.preventDefault)
                {
                    e.preventDefault();
                    e.stopPropagation();
                }
            }
            return e;
        };
    }(document.createElement('div')));
    //instead of using the HTML onclick attribute:
    document.getElementById('buttonID').onclick = flip;//use as event handler
};

      

Please note what window.onload

is causing the memory leak in IE <9, check this link to resolve this issue

0


source







All Articles