Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  145] [ 1]  / answers: 1 / hits: 171491  / 15 Years ago, wed, october 7, 2009, 12:00:00

It seems that experienced web developers frown upon using document.write() in JavaScript when writing dynamic HTML.


Why is this? and what is the correct way?


More From » html

 Answers
21

document.write() will only work while the page is being originally parsed and the DOM is being created. Once the browser gets to the closing </body> tag and the DOM is ready, you can't use document.write() anymore.



I wouldn't say using document.write() is correct or incorrect, it just depends on your situation. In some cases you just need to have document.write() to accomplish the task. Look at how Google analytics gets injected into most websites.



After DOM ready, you have two ways to insert dynamic HTML (assuming we are going to insert new HTML into <div id=node-id></div>):




  1. Using innerHTML on a node:



    var node = document.getElementById('node-id');
    node.innerHTML('<p>some dynamic html</p>');

  2. Using DOM methods:



    var node = document.getElementById('node-id');
    var newNode = document.createElement('p');
    newNode.appendChild(document.createTextNode('some dynamic html'));
    node.appendChild(newNode);



Using the DOM API methods might be the purist way to do stuff, but innerHTML has been proven to be much faster and is used under the hood in JavaScript libraries such as jQuery.



Note: The <script> will have to be inside your <body> tag for this to work.


[#98557] Thursday, October 1, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madelyn

Total Points: 449
Total Questions: 100
Total Answers: 100

Location: Seychelles
Member since Fri, May 7, 2021
3 Years ago
madelyn questions
Wed, Jul 28, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
Sat, Nov 7, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;