Skip to content
Advertisement

How to use generate multiple of something with a single function using vanilla JS?

In the snippet below, I’m generating a single math problem on load, and if the New Problem button is clicked, the problem will refresh with a new one.

I want 3 problems to be able to display on the page. In pseudo code, this would be:

forEach class called .problem, display a different math problem.

This is what I have thus far, but I’m not getting the result I need.

let getAddition = () => {
  let max = 10;
  let rand1 = Math.floor(Math.random() * 10) + 1;
  let rand2 = Math.floor(Math.random() * 10) + 1;
  let sum = rand1 + rand2;
  let problems = document.querySelectorAll('.problems');
  
  problems.forEach((problem) => {
    problem.textContent = `${rand1} + ${rand2} = ${sum}`;
  });
};

window.addEventListener('onload', getAddition());
newProblem.onclick = () => {
  getAddition();
};
<button type="button" id="newProblem">New Problem</button>
<div class="container">
  <div class="problem"></div>
  <div class="problem"></div>
  <div class="problem"></div>  
</div>

Advertisement

Answer

First thing should be your selector. .problem is what you have in your class.

Second thing, move the random number calculation inside the loop to get different problem.

let getAddition = () => {
  let max = 10;
  
  let problems = document.querySelectorAll('.problem');
  
  problems.forEach((problem) => {
    const rand1 = Math.floor(Math.random() * 10) + 1;
    const rand2 = Math.floor(Math.random() * 10) + 1;
    const sum = rand1 + rand2;
    problem.textContent = `${rand1} + ${rand2} = ${sum}`;
  });
};

window.addEventListener('onload', getAddition());
newProblem.onclick = () => {
  getAddition();
};
<button type="button" id="newProblem">New Problem</button>
<div class="container">
  <div class="problem"></div>
  <div class="problem"></div>
  <div class="problem"></div>  
</div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement