irontamoor
irontamoor

Reputation: 33

Rather than document.write, outputting in id/class of div

I’m trying to change the document.write to outputting in idor class so I can add it to a div I tried to use document.getElementById("demo").innerHTML but it doesn't seem to work, not sure if I’m doing it correctly.

<html>
<body>
<p id="demo"></p>
<script type="text/javascript">
var d=new Date()
var daynumber=new Array("0","1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13th","14th","15th","16th","17th","18th","19th","20th","21st","22nd","23rd","24th","25th","26th","27th","28th","29th","30th","31st","32nd")
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var monthname=new Array("January","Febuary","March","April","May","June","July","August","September","October","November","December")
document.write(weekday[d.getDay()] + " ")
document.write(daynumber[d.getDate()] + " ")
   // document.write(d.getDate() + " ")
document.write(monthname[d.getMonth()] + " ")
document.write(d.getFullYear())
</script>

</body>
</html>

Check Output or Edit Code on jsfiddle

Upvotes: 2

Views: 370

Answers (3)

Chris Barr
Chris Barr

Reputation: 34012

You can use document.getElementById('idname') or even document.querySelector('#idname')

Here's a small demo with your code

//Vars
var d = new Date();
var outputElement = document.getElementById("current-date");

//Date Text arrays
var daynumber = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th", "30th", "31st", "32nd"];
var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var monthname = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

//Build up a string
var dateStr = weekday[d.getDay()] +
  ", the " + daynumber[d.getDate() - 1] +
  " of " + monthname[d.getMonth()] +
  ", " + d.getFullYear();

//Output to screen
outputElement.innerHTML = dateStr
#current-date {
  padding: 1px 4px;
  background: #EFEFEF;
  border: 1px solid #CCC;
  border-radius: 4px;
}
<p>
  Today's date is <strong id="current-date"></strong>
</p>

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386600

You could assign a new fuction with a closure over the target element.

But, as Chris Barr pointed out, "Overwriting built-in JavaScript functions is a bad idea."

document.write = (element => string => element.innerHTML += string)(document.getElementById('out'));

document.write('foo<br>');
document.write('bar');
<div id="out"></div>

Upvotes: 0

abhinavsinghvirsen
abhinavsinghvirsen

Reputation: 2014

It might help you

document.getElementById("demo").innerHTML = weekday[d.getDay()] + " "+daynumber[d.getDate()] + " "+monthname[d.getMonth()] + " "+d.getFullYear();

Upvotes: 2

Related Questions