0

Is it possible to insert html into classes like so? It's not working and I have no errors in the console.

<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>

<script>
    var currentYear = new Date().getFullYear();
    var yearTarget = document.getElementsByClassName("yearTarget");
    yearTarget.innerHTML = currentYear;
</script>
chilledMonkeyBrain
  • 141
  • 1
  • 4
  • 15

2 Answers2

2

Document.getElementsByClassName() returns an array-like object. You have to either specify index or iterate through all the elements to set innerHTML individually:

var currentYear = new Date().getFullYear();
var yearTarget = document.getElementsByClassName("yearTarget");
[...yearTarget].forEach(function(el){
  el.innerHTML = currentYear;
});
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

document.getElementsByClassName("catlink")is selecting all the elements in webpage as array therefore you have to use [0]

yearTarget[0].innerHTML = currentYear;
Osama
  • 2,912
  • 1
  • 12
  • 15