I understand how to display the current year and pass it through an ID, but the ID, of course, will only display once. I need to be able to display it multiple times throughout the site.
How do I accomplish this?
//get year
var yyyy = new Date().getFullYear();
currYear.innerHTML = yyyy;
//trying to display as a class
document.getElementsByClassName('thisYear')[0] = yyyy;
<span id="currYear"></span>
<span class="thisYear"><span>
From what i understand, you are trying to add the current year to multiple element in your HTML ? Currently, you are only assigning it to the first one ( [0]
).
You could parse each element with the class thisYear
and add the current year to them.
//get year
var yyyy = new Date().getFullYear();
//trying to display as a class
//the document.getElementByClassName returns a htmlCollection. not an array directly.
//https://stackoverflow.com/a/3871602/5784924
Array.from(document.getElementsByClassName('thisYear')).forEach(function(element) {
element.innerHTML = yyyy;
});
<div class="thisYear">this year</div><br>
<div class="thisYear">this year</div><br>
<div class="notThisYear"> not this year</div><br>
<div class="notThisYear">not this year</div><br>
<div class="thisYear"></div>
P.S. this answer reflect only what was asked by OP. If you wish see something more up to date and browser compliant, please see Scott Marcus' answer.