Moira Moira - 2 months ago 5
Javascript Question

Attempting to write to document but nothing is loading

So this is my first attempt at Javascript and it's probably really messy. The whole point of it is to output the date with each part of the date being different colours. I've looked at a few ways of doing it and this is what I've come up with (HTML added by request):


<p id="calendar"></p>

var d = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var colors = ["red", "green", "yellow", "blue", "brown"];
var i;
var fulldate = [];

var fulldate[0] = days[d.getDay()];
var fulldate[1] = d.getDate();
var fulldate[2] = months[d.getMonth()];
var fulldate[3] = d.getFullYear();
var hours = d.getHours();
var minutes = d.getMinutes();
var fulldate[4] = hours + ":" + minutes

for(i = 0; i < 5; i++){
document.getElementById("calendar").innerHTML = "<span style=\"color:"colors[i]"\">" fulldate[i] "</span>"

I'm trying to work out why it's not displaying anything at all in the paragraph tag I've written. Can anyone see where I've gone wrong?


You're nearly there!

Couple of things that you could do with doing:

1. You need to concatenate your strings and variables where you're setting the innerHTML of your p element using the + symbol between string and variable

e.g. "A string" + myVariable or aVariable + "some string" + anotherVariable

2. Initialize i (the counter for your for loop) within the for declaration - you don't need to declare this before your loop, and it's easier to read in future

Remove the var i; declaration near the top - it's a bit lost. Then, in your for(...) statement, you can just initialize i, there.

e.g. for(var i = 0; i < 5; i++) { ... }

3. You're replacing the innerHTML of your #calendar every iteration of the for loop. You can use += to append to an existing value.

e.g. document.getElementById('calendar').innerHTML += "...";

Your code should look something like this:

for (var i = 0; i < 5; i++) {
        .innerHTML += "<span style=\"color:" + colors[i] + "\">" + fulldate[i] + "</span>";

Hope this helps :)