I've been given some JavaScript that creates a digital clock to go onto a webpage. This is working perfectly, however I'm trying amend it to wrap the am/pm suffix (or diem in this code) in span or bold tags so that I can style it differently to the rest of the time in the CSS.
I'm sure this would be really simple for someone that knows what they're doing but I'm really struggling. Any help would be appreciated, the JavaScript is below:
function renderTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
setTimeout('renderTime()',1000);
if (h == 0) {
h = 12;
} else if (h > 12) {
h = h - 12;
diem="PM";
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent = h + ":" + m + " " + diem;
myClock.innerText = h + ":" + m + " " + diem;
var diem = document.createElement('span');
}
renderTime();
You have a few options:
Use innerHTML instead of innerText. That allows you to insert HTML tags into the string:
myClock.innerHTML = h + ":" + m + " <span>" + diem + "</span>;
Use appendChild and leave out the diem at the end of the innerText:
myClock.innerText = h + ":" + m + " ";
var diemSpan = document.createElement('span');
diemSpan.innerText = diem;
myClock.appendChild(diemSpan);
Finally, you could put a clockDisplay and a diem span within your markup and access them appropriately:
Markup:
<div id="clockDisplay">
<span id="clockDisplay-time"></span>
<span id="clockDisplay-suffix"></span>
</div>
Script:
document.getElementById("clockDisplay-time").innerText = h + ":" + m;
document.getElementById("clockDisplay-suffix").innerText = diem;
Try this:
var myClock = document.getElementById('clockDisplay');
var suffix = document.createElement('span');
suffix.innerText = diem;
myClock.innerText = h + ":" + m + " ";
myClock.append(suffix);
Or, if you want to be more efficient (pure DOM manipulation):
var myClock = document.getElementById('clockDisplay');
var suffix = document.createElement('span');
suffix.append(document.createTextNode(diem));
myClock.append(document.createTextNode(h + ":" + m + " "));
myClock.append(suffix);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With