medzvre gena
medzvre gena

Reputation: 145

advice how to make this code drier than it is now

I am trying to reach this without usign so many main .textcontents

  main[0].textContent = randomNumber();
  main[1].textContent = randomNumber();
  main[2].textContent = randomNumber();
  main[3].textContent = randomNumber();
  main[4].textContent = randomNumber();

Tried to loop through it but something does not work here is my code

<HTML>
 <div id="number-main" class="number-main">
          <div class="main" id="main1">0</div>
          <div class="main" id="main2">0</div>
          <div class="main" id="main3">0</div>
          <div class="main" id="main4">0</div>
          <div class="main" id="main5">0</div>
  </div>
</html>
const main = document.getElementsByClassName("main");
let points = [main[0], main[1], main[2], main[3], main[4]];


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


function myFunction() {
   for (let i = 0; i < points.length; i++) {
    return (points[i].textContent = randomNumber());
  }
}

Upvotes: 1

Views: 32

Answers (2)

RoToRa
RoToRa

Reputation: 38410

First off, this line

let points = [main[0], main[1], main[2], main[3], main[4]];

is a bit strange, because you don't need to do it. While getElementsByClassName doesn't return an array, it does return a HTMLCollection which can be looped over with a for loop just as you did, so just can do:

const points = document.getElementsByClassName("main");

However if you ever do need to convert it to an array, there are better ways, than enumerating all the items manually, for example, with the spread operator:

const main = document.getElementsByClassName("main");
const points = [...main];

Or the Array.from method:

const main = document.getElementsByClassName("main");
const points = Array.from(main);

Your actually error here, is that you are using the return statement inside the for loop. return exits a function immediately, in your case while in the first iteration of the loop which aborts running the loop. Since your function doesn't need to actually return anything, you don't need to use it:

function myFunction() {
   for (let i = 0; i < points.length; i++) {
    points[i].textContent = randomNumber();
  }
}

Upvotes: 1

GitGitBoom
GitGitBoom

Reputation: 1912

Something like this?

document.querySelectorAll('.main').forEach(
  div => div.textContent = Math.floor(Math.random() * 50)
)
 <div id="number-main" class="number-main">
          <div class="main" id="main1">0</div>
          <div class="main" id="main2">0</div>
          <div class="main" id="main3">0</div>
          <div class="main" id="main4">0</div>
          <div class="main" id="main5">0</div>
  </div>

Upvotes: 1

Related Questions