Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 680
Hai Tien Avatar asked Oct 05 '13 11:10

Hai Tien


People also ask

How do I add text inside a div?

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.

Can I append to a div JavaScript?

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')

What is the difference between append and appendChild in JavaScript?

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.


1 Answers

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

like image 99
Sergio Avatar answered Oct 24 '22 14:10

Sergio