user1272441
user1272441

Reputation: 3

Display date with JavaScript in a specific html tag

I have this simple Java Script code to display the date. I want to take the results from the js, and to show them within a specific html in the document. Example; div, p, h3, etc. If I place the script in the tag, it will overwrite my existing html page. How can I display the date in a specific tag within the html page?

<script language="JavaScript">
<!--
var current_date = new Date ( );

var month_names = new Array ( );
month_names[month_names.length] = "January";
month_names[month_names.length] = "February";
month_names[month_names.length] = "March";
month_names[month_names.length] = "April";
month_names[month_names.length] = "May";
month_names[month_names.length] = "June";
month_names[month_names.length] = "July";
month_names[month_names.length] = "August";
month_names[month_names.length] = "September";
month_names[month_names.length] = "October";
month_names[month_names.length] = "November";
month_names[month_names.length] = "December";

document.write ( month_names[current_date.getMonth()] );
document.write ( " " + current_date.getDate() );
document.write ( " " );
document.write ( " " + current_date.getFullYear() );
// -->
</script>

Upvotes: 0

Views: 2533

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92314

You almost never use document.write for the reason you mentioned. That is, if applied after the page has finished rendering, it will overwrite the existing page.

just do

document.getElementById('id-of-element-to-write-into').innerHTML = 
    month_names[current_date.getMonth()] +
    " " + current_date.getDate() +
    " " + current_date.getFullYear()

Instead of document.getElementById, you can also use

or just

Upvotes: 3

slowBear
slowBear

Reputation: 263

var months = [ //create the months
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
], d, m, y, now, out_string; //vars to hold date, month, year, date object and output string
now = new Date(); //new date object
d = now.getDate(); //current date
m = now.getMonth(); // current month
y = now.getFullYear(); //current year


out_string = months[m] + ' ' + d + ' , ' + y; //concat date parts into output string 

document.getElementById('yourIDHere').innerHTML = out_string; //set the html of the hmtl element to the output string

http://jsfiddle.net/22MVm/1/

Upvotes: 1

Related Questions