Reputation: 1629
im trying to add a css class in my javascript code but when i preview it in the browser it dont seem to work
heres the code
<script>
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var dayarray=newArray("Sunday","Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday")
var montharray=newArray("January","February","March","April","May","June",
"July","August","September","October","November",
"December")
document.write(""+dayarray[day]+" "+daym+" "+montharray[month]+" "+year+"")
.className = 'bigdate';
</script>
Here's the CSS:
.bigdate{
color:#03C;
}
Upvotes: 0
Views: 170
Reputation: 114447
document.write(""+dayarray[day]+" "+daym+" "+montharray[month]+" "+year+"").className = 'bigdate';
Should be:
document.write("<div class='bigdate'>"+dayarray[day]+" "+daym+" "+montharray[month]+" "+year+"</div>").
You need to have an HTML element to have a class name.
Upvotes: 0
Reputation: 349262
You should not use document.write
to update the document. Update the document by setting the innerHTML
property, or appending an element.
<div id="my-element"></div>
<script>
....
var elem = document.getElementById('my-element');
elem.innerHTML = dayarray[day]+" "+daym+" "+montharray[month]+" "+year;
elem.className = 'bigdate';
</script>
className
is a property which refers to the class
attribute. document.write()
has no return value, so no properties. Even if you want to use document.write()
, then you have to use HTML tags, and add class="bigdate"
:
document.write('<div class="bigdate">' + ..... + '</div>');
Upvotes: 1
Reputation: 490667
That's not how document.write()
works, it doesn't return a reference to the node(s) that it wrote.
Try...
document.write("<span class=\"bigdate\">"+dayarray[day]+" "+daym+" "+montharray[month]+" "+year+"</span>");
...or better still...
var span = document.createElement('span');
span.appendChild(document.createTextNode(dayarray[day]+" "+daym+" "+montharray[month]+" "+year+));
document.body.appendChild(span);
Upvotes: 6