Beginner javascript/jquery - document.write

147 views Asked by At

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

There are 1 answers

3
Shan Robertson On

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();