randomly replace contents in <li>

Viewed 34

I am trying to make a simple game in JS, where the sum of two random number will be generated, And there is four < li > tag which contains also some randomly generated number. The sum result will be placed one of this < li > tag. User has to find the right < li > and click on it. I am not understanding how to place the sum result in those four < li > randomly. Could you please help?

        let number1     = Math.floor(Math.random() * 100)
        let number2     = Math.floor(Math.random() * 100)
        const title     = document.querySelector(".title")
        title.innerHTML = 'What is the sum of '+ number1  + ' and ' + number2 ;

        const num1      = document.querySelector(".nums1");
        num1.innerHTML  = Math.floor(Math.random() * 100) 
        const num2      = document.querySelector(".nums2"); 
        num2.innerHTML  = Math.floor(Math.random() * 100) 
        const num3      = document.querySelector(".nums3");
        num3.innerHTML  = Math.floor(Math.random() * 100) 
        const num4      = document.querySelector(".nums4");
        num4.innerHTML  = Math.floor(Math.random() * 100) 

        let sum = number1 + number2
        console.log(sum)
      
        // this function i have made to generate random numbers from 1-3, 
        //when the number is 1, the 1st li number will contain the sum result
        // when the number is 2, the 2nd li will contain the sume result and so on..

        function randPosition(){
            let randomsPos = Math.floor(Math.random() * 4)+1          
        }
        randPosition()
    <div class="container">
     <h1 class="title">What is the sum of 10 and 4 ?</h1>
      <div class="list">
        <ul>
         <li class="nums1">9</li>
         <li class="nums2">4</li>
         <li class="nums3">6</li>
         <li class="nums4">7</li>
        </ul>
       </div>
       <button class="btn"> Play Again</button>
    </div>

1 Answers

Using the :nth-child selector will help in this case.

Modify the randPosition function as below

function randPosition(){
    let randomsPos = Math.floor(Math.random() * 4)+1
    const liElement = document.querySelector(`ul :nth-child(${randomsPos})`);
    liElement.innerHTML = sum;
}

The :nth-child selector will select the nth child element of the ul. And the content will be replaced with the sum

Related