Click here to Skip to main content
15,034,986 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a div and I want the date in there. The following code includes document.write. So the text will appear in a plain document. How can I avoid this and let the text appear in the div? The div has the id "appear".

<script type="text/javascript">

var date=new Date();
var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";

document.write(month[day.getMonth()]);

</script> 
Posted
Updated 11-Mar-12 9:51am
v2

1 solution

You can do it using the property innerHTML which all elements have, for example.
JavaScript
myDiv = document.GetElementById("myDivId");
myDiv.innerHTML = month[day.getMonth()]; // you can add any HTML markup here

You need to mark the target div with matching id attribute:
HTML
<div id="myDivId"></id>


At first, you can put some content inside this div or leave it empty. If would be filled in by the fragment of JavaScript code shown above.

—SA
   
v2
Comments
Chi Ller 11-Mar-12 17:29pm
   
I didn´t know that innerHTML can replace a document.write. So thank you
Sergey Alexandrovich Kryukov 11-Mar-12 18:21pm
   
You are very welcome.

You know now.
It's not replacement of write, it's replacement of inner HTML code of any element.

I would also recommend to use jQuery, it makes JavaScript programming way more compact, better for portability, maintenance, and more.
--SA
Sergey Alexandrovich Kryukov 11-Mar-12 18:22pm
   
And innerHTML is much better, because otherwise you would re-write the whole document, this is not even always feasible.
--SA
Chi Ller 12-Mar-12 12:33pm
   
That was the big problem
Sergey Alexandrovich Kryukov 12-Mar-12 13:16pm
   
Well, good luck to get some more... :-)
Best wishes,
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900