Minh Anh Minh Anh - 1 month ago 5
HTML Question

Javascript : Append text into div?

I want use javascript to append clock into inside of a div. Here is my code :

<script type="text/javascript">
//<![CDATA[
function makeArray() {
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}

var months = new makeArray('January','February','March','April','May',
'June','July','August','September','October','November','December');
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;

var timer = document.write(months[month]+ " " +day + ", " + year);
document.getElementById('time').appendChild(timer);
//]]></script>

<div id='time'></div>


But it doesn't work. Help me for fixing it. Thanks you.

Answer

Try this:

var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth();
var yy = date.getFullYear();
var year = (yy < 100) ? yy + 1900 : yy;

var timer = document.createElement('div');
timer.innerHTML = months[month] + " " + day + ", " + year;
document.getElementById('time').appendChild(timer);

Demo here

Comments