1

So far I only know how to write code for AFTER the html has loaded. How do I use a function like this:

function makeBranches(){
    document.write("<center>")
    var bq = 10;
    for (var run = 0;run<bq;run++){
        for (var length=0;length<=run;length++)
            document.write("<font color=green><b>^</b></font>");
        document.write("<br>");

    }
    document.write("</center>");
}

inside of $(document).ready, without it overwriting the html?

1
  • 2
    Don't use document.write. Use append or html and text functions in jQuery instead. Commented Nov 28, 2014 at 0:35

1 Answer 1

1

document.write replaces your document. If you just want this code in the body of your document, simply replace document.write with document.body.innerHTML += 'my code'. I use the += operator because you are appending multiple things. if you simply did = it would replace every time, whereas += takes the current html in your body, replaces it with itself plus what you just added.

And to target another element you can do document.querySelector(element).innerHTML; or jquery $(element).html();

Sign up to request clarification or add additional context in comments.

3 Comments

"document.write replaces your document." Only under specific circumstances, not in general.
it was my understanding that calling document.write also calls document.open which clears the document. But I never used document.write as it's not very useful in 99% of cases hah
It only calls document.open if document.close as been called. Which happens when the browser finished parsing the HTML. So if you call document.write beforehand, the markup will just be inserted where it was called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.