WilkyRL
WilkyRL

Reputation: 35

Get document HTML before document.write();

I would like to be able to get a page's HTML as a string before the page loads and document.write(); is called using my javascript extension. Is it possible to get some or all of a page's HTML before it loads? Thank you for the help

Upvotes: 1

Views: 498

Answers (3)

Wayne Smith
Wayne Smith

Reputation: 4868

document.write takes place before document.$( document ).ready() or document.onload. A document.write after onload event (the signal the page has loaded) overwrites the document. So for setting portions of the page using javascript the best practice is general to use getElementById and write to it.

The only things available during document.write are those things above it in the document file, and it is not a document feature but rather a normal implementation.

IE

<p id="line1">1st line of html output</p>
<script>
alert(document.getElementById("line1").innerText);
</script>
<script>
alert(document.getElementById("lastline").innerText);
</script>
<p id="lastline">last line of html output</p>

Normally results in a alert box with "1st line of html output"

Followed by an error in console ... Uncaught TypeError: Cannot read property 'innerText' of null


An alternative solution is to display:none the page. Modify the page then use a transaction effect to cause the page to be displayed. Which gives the same appearance to the user.

Upvotes: 1

Adam
Adam

Reputation: 11

Try load page using jQuery ajax

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "page.html",
        data: { },
        success: function(data){
            // in data is returned page.html html code
        }
    });
});

document.documentElement.innerHTML or document.documentElement.outerHTML will store page code loaded only before that script

Upvotes: 1

TROGER Anthony
TROGER Anthony

Reputation: 47

Try this :

document.documentElement.innerHTML

or that :

document.documentElement.outerHTML

Upvotes: 1

Related Questions