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.
Use the insertAdjacentText() method to append text to a div element, e.g. container. insertAdjacentText('beforeend', 'your text here') . The method inserts a new text node at the provided position, relative to the element it was called on.
HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')
Difference between appendChild() and append() append() also allows you to append DOMString objects, and it has no return value. Further, parentNode. appendchild() allows you to append only one node, while parentNode. append() supports multiple arguments - so you can append several nodes and strings.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With