-2

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>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Millhorn
  • 2,953
  • 7
  • 39
  • 77
  • `document.getElementsByClassName('thisYear')[0]` <-- [This is terrible code](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474). – Scott Marcus Nov 01 '19 at 15:22
  • *display it multiple times throughout the site.* <-- Then you'll need to store it so that each page can access it. You could use cookies or `localStorage` to do that. This has nothing to do with `id`s or classes. – Scott Marcus Nov 01 '19 at 15:23
  • This is why I'm here @ScottMarcus. I have tried and can't get it to work. Now, if you know all that... why not make a constructive addition to the conversation? Storing in local storage is far too much for something like this. In the answer below, you can see that a forEach loop is what I really needed. – Millhorn Nov 01 '19 at 15:37
  • Base on what you wrote *"display it multiple times throughout the site."*, `localStorage` is what you'd need and is constructive. The fact that you say that the answer below shows what you needed indicates that you didn't ask the right question because there's nothing in it that addresses using the year throughout the site. – Scott Marcus Nov 01 '19 at 15:41
  • Display it multiple times throughout the site. In a title here, or a paragraph there. In the future, would that be a clearer picture? – Millhorn Nov 01 '19 at 15:46
  • 1
    No, because when the same data needs to be displayed multiple times in a **site**, you need to store it somewhere so you don't have to generate that data over and over again, hence cookies or `localStorage`. It appears now that your question really is *"How do I populate several elements on a **page** that have the same class with the same data."* – Scott Marcus Nov 01 '19 at 15:48
  • Thanks @ScottMarcus. I will remember to be more clear next time. – Millhorn Nov 01 '19 at 18:39

3 Answers3

3

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.

Nicolas
  • 8,077
  • 4
  • 21
  • 51
  • [`getElementsByClassName()` is NOT the correct thing to do](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474) and putting it in a loop only makes matters worse. Use `querySelectorAll()`. – Scott Marcus Nov 01 '19 at 15:43
  • 1
    In this case, we are not putting it in a loop, we are getting the values and parsing those. I understand why `querySelectorAll` is better but since i'm trying to answer the question asked, i want to use most of OP's code possible. Thanks for the advice though. @ScottMarcus – Nicolas Nov 01 '19 at 15:48
  • The loop issue relates to the use of `.innerHTML`. `.innerHTML` has performance issues on its own, but should never be used in a loop because you wind up modifying the DOM over and over, each time causing re-paints and re-flows. First, in this case the data doesn't contain any HTML, so `.innerHTML` shouldn't even be used, `.textContent` should. But, if you did have HTML, you should use the loop to build up a string of HTML and then after the loop, inject it just one time into the DOM with `.innerHTML`. – Scott Marcus Nov 01 '19 at 15:52
  • 1
    IMHO if we don't educate new coders about bad code that is 25+ years old and should no longer be used or bad API usage, we'll continue to see that bad code in modern applications. `.getElementsByClassName()` (and it's legacy counterparts) should never be used in 2019. The only reason we still see it everywhere is because people don't know any better and they just copy someone else's code that seems to "work". – Scott Marcus Nov 01 '19 at 15:53
  • If you find my answer not good in any ways, feel free to post your own. I will happily upvote it. You have good points and i'm afraid they might be overlooked in comments. @ScottMarcus – Nicolas Nov 01 '19 at 15:57
  • Done. Take a look and note that `Array.from()` doesn't solve the `.forEach()` not supported issue because IE doesn't support `.forEach()` nor does it support `Array.from()`. You have to use code that was standard while IE was being maintained. – Scott Marcus Nov 01 '19 at 16:15
2

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>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

I guess you're trying to assign the current date to multiple elements witht the same class, if so. Please take a look at this example below.

var items = document.getElementById( 'items' ),
    divs = document.getElementsByClassName( 'count' );

[].slice.call( divs ).forEach(function ( div ) {
    div.innerHTML = items.innerHTML;
});

Source: Replace innerHTML of all divs with same class