As you may have known, JavaScript’s document.write has some issues. It will render the text directly in place, and if the page itself has been rendered, then it may override the whole page.

Recently, I had to deal with the existing function that use document.write to render the content of an element. I didn’t create the function and the function itself is used in other places.

So, what I did is overwriting document.write.

Let’s assume that printSomething function use document.write for rendering.

<div id="div1">
   <script type="javascript">

I need to change div1 content after the page is loaded and I still need to call printSomething then the following function reflects what I do.

function changeDivContent(message){
    var tmp = document.write;
    var newContent = '';
    document.write = function(){
        var arr=[];
        arr.push.apply(arr, arguments);
        newContent += arr.join(''); 
    document.getElementById('div1').innerHTML = newContent;
    document.write = tmp;

Basically I overwrite the document.write function to concat the arguments object in newContent variable instead of rendering the content.

While it is not a good practice, it still works !