3

I modified a little js script which compares a date to today and calculates the difference. (I'm a novice) However, it uses document.write, which I've been told is bad. I don't know why it's bad, people just say it's bad and never explain why. Anyway, I'm looking for an alternative. innerHTML doesn't seem to work, and other questions answered on this site just point to DOM manipulation references without really answering the question.

Here's my script:

    //Set the two dates
    var iquit =new Date(2013, 1, 15);
    today=new Date();
    //Get 1 day in milliseconds
    var one_day=1000*60*60*24;
    var day_numeric=Math.ceil((today.getTime()-iquit.getTime())/(one_day));
    //Calculate difference btw the two dates, and convert to days
    document.write("<p>"+day_numeric+
            " days have gone by since you quit smoking!</p>"+
            "<p>You have saved "+ day_numeric*7+" pounds</p>");

If anyone can tell me a better way to write this, it'd be amazing.

dmc
  • 258
  • 5
  • 17
  • The most common solution is to use `innerHTML`. What does "does not work" mean here? – Sirko Feb 18 '13 at 09:44
  • Haven't seen [this SO answer](http://stackoverflow.com/a/802943/1169519) yet? It explains, why `document.write` is "bad". – Teemu Feb 18 '13 at 09:46
  • Thanks for the link to the explanation! By "Does not work" it does not write to the DOM. – dmc Feb 18 '13 at 09:51
  • Both `document.write()` and `innerHTML` should work. Are you sure, that you're not outputting to a hidden / covered element? BTW, the calculation inside of the DW's argument may result `NaN`, it's better to enclose it within parentehes. – Teemu Feb 18 '13 at 10:03
  • I think you will find this helpful: http://www.netmagazine.com/tutorials/javascript-debugging-beginners. – Felix Kling Feb 18 '13 at 10:05
  • That was not helpful Felix. – dmc Feb 18 '13 at 10:18

3 Answers3

2

The problem with document.write() is that if you call it after the DOM is ready, it will overwrite the existing DOM. This SO answer has a more extensive explanation to why document.write() rarely is the best choice.

Using .innerHTML should work fine, but you need to select the element you want to add the content do. So something like this:

document.getElementById("idOfSomeElement").innerHTML = "your content";

Live example

What method to use to get the proper element depends on what you have to select on, but if possible, the easiest way is probably to attach an ID to the element you want to add content to, and use the above method.

Community
  • 1
  • 1
Christofer Eliasson
  • 29,772
  • 6
  • 69
  • 99
  • Thanks for the explanation, I tried this though and had no success. – dmc Feb 18 '13 at 09:55
  • @dmc In what way did it not work? Added a link to an example in my answer. Could it be that you are running your code before the DOM is ready? Try moving your code to the end of your body-element, just before the closing body-tag. – Christofer Eliasson Feb 18 '13 at 10:04
  • Thank you, this worked, and thank you for explaining the placement. I'd been running the code in the head, and nothing was being output, no matter what I tried. – dmc Feb 18 '13 at 10:17
  • @dmc My pleasure, glad it helped! – Christofer Eliasson Feb 18 '13 at 10:20
2

If you're using pure JavaScript, one of best ways to get this may be:

var paragraph1 = document.createElement("p");
paragraph1.appendChild(document.createTextNode(day_numeric+" days have gone by since you quit smoking!"));

var paragraph2 = document.createElement("p");
paragraph1.appendChild(document.createTextNode("You have saved "+ day_numeric*7+" pounds"));

document.body.appendChild(paragraph1);
document.body.appendChild(paragraph2);

100% standard DOM.

About document.write: good or evil...

I guess some consider document.write as a bad practice because it's the lower-level way of output raw content to the (X)HTML document.

Since (X)HTML is basically a dialect of XML (or at least, based on XML and SGML), the right and expected way of writing a document is creating nodes and appending them to the whole document.

document.write writes the content after the last written element and you lose a lot of control when you want to decide where to place the newly-created element in the document.

For example, would you output a paragraph from a JavaScript function loaded in the from the <head> element? It would be hard as it'll not be rendered in the body necessarily. That's too bad.

It's better to create DOM elements/nodes and append them to the document using appendChild(...).

Community
  • 1
  • 1
Matías Fidemraizer
  • 59,064
  • 16
  • 107
  • 181
0

Check this link for reasons why it is considered bad practice: Why is document.write considered a "bad practice"?

And how are you using innerHTML?

Have you tryed something like

<script>
...
document.getElementById('container-id').innerHTML = "<p>"+day_numeric+" days have gone by since you quit smoking!</p>"+"<p>You have saved "+ day_numeric*7+" pounds</p>";
</script>

This requires an element with the container-id id somewhere in the page, like:

<div id='container-id'></div>
Community
  • 1
  • 1
cernunnos
  • 2,698
  • 1
  • 16
  • 17
  • Thank you. I tried this method and it did not write to the page. – dmc Feb 18 '13 at 09:59
  • Both innerHTML and the appendChild suggestion from Matías have to work, if they dont its because of some other problem. Are you sure the javascript code is running? (you can check that in most browsers using console.log("hello world") for instance, or even easier, alert("hello world")). Additionally, are you sure your HTML code has a body? Try using the inspect tool of your browser to check if you are not writting content into the head of the HTML document. – cernunnos Feb 18 '13 at 10:56