0

want to change the text in div.main1 but innerText does not work. although in console it gives me random number I still can not change inner text in div.main1

enter code here

<HTML>
<div class="container">
      <h3 class="text">Good Luck!</h3>
      <div class="numbers">
        <div class="number-main">
          <div class="main main1">0</div>
          <div class="main main2">0</div>
          <div class="main main3">0</div>
          <div class="main main4">0</div>
          <div class="main main5">0</div>
        </div>
        <div class="number-secondary">
          <div class="secondary">0</div>
          <div class="secondary">0</div>
        </div>
      </div>
    </div>

</html>

enter code here

<script>
    const main1 = document.getElementsByClassName("main1");

   function randomNumber() {
      return Math.floor(Math.random() * 50);
    }

   main1.innerText = randomNumber();
</script>
medzvre gena
  • 115
  • 1
  • 1
  • 9

2 Answers2

2

getElementsByClassName returns a list. You need to add an id to select a specific DOM, or use its index:

main1[0].innerText = randomNumber(); <- the first main1 it finds
GAEfan
  • 11,244
  • 2
  • 17
  • 33
1

document.getElementsByClassName returns a collection of elements, not a single element. Even if there is only one element returned, it is still returned as a collection.

You need to use it like an array and grab the first element it returns

const main1 = document.getElementsByClassName("main1")[0];

function randomNumber() {
    return Math.floor(Math.random() * 50);
}

main1.innerText = randomNumber();
Dan Mullin
  • 4,285
  • 2
  • 18
  • 34