document.getElementsByClassName('thisYear')[0] = yyyy;
attempts to set the DOM element returned from the call to the year, rather than some property of the DOM element to the year.
To make your code work, the "quick fix" is to add .innerHTML
to your line:
document.getElementsByClassName('thisYear')[0].innerHTML = yyyy;
However, .getElementsByClassName()
(along with similar APIs from the
1990s, like getElementsByTagName()
, getElementsByName()
and
others) should no longer be used. I've written about this and the idea
of adding an index to the end of a method that returns a node list
here.
Instead, use the modern, standards-compliant .querySelector()
and .querySelectorAll()
and then you'll need to loop through the collection and modify the elements individually.
See the additional comments inline:
//get year
var yyyy = new Date().getFullYear();
// .querySelectorAll returns a node list, which is not an actual Array implementation.
// IE doesn't support calling .forEach on node lists, so if you need to support IE
// you'll need to convert the node list into an aray in order to call .forEach and you'll
// need to do it in a way that IE understands (not Array.from()):
// Array.prototype.slice.call(document.querySelectorAll('.thisYear')).forEach(function(element) {
// But, if you are not concerned with IE, you can call .forEach() directly on the node list
document.querySelectorAll('.thisYear').forEach(function(element) {
// When the content you wish to update doesn't contain any HTML, don't use .innerHTML
// which has performance and potential security implications, use .textContent instead
element.textContent = yyyy;
});
div { margin-bottom:1em; }
<div class="thisYear">this year</div>
<div class="thisYear">this year</div>
<div class="notThisYear"> not this year</div>
<div class="notThisYear">not this year</div>
<div class="thisYear"></div>