Why I can't display a div when I push the button?

Hello I want to make one of my divs appear randomly each time I push the button, but something on my code appears no to be working, and I don’t know what it is, help please.
codepen
HTML

<div class="mega">
    <div class="manyDivs div1"></div>
    <div class="manyDivs div2"></div>
    <div class="manyDivs div3"></div>
    <div class="manyDivs div4"></div>
    <div id="myPicture"></div>
    <button onclick="run()">click me</button>
</div>

CSS

.manyDivs {
    margin: 10px;
    width: 200px;
    height: 200px;
    border: 1px solid #000;
}
.div1 {background-color: coral;}
.div2 {background-color: firebrick;}
.div3 {background-color: violet;}
.div4 {background-color: palegreen;}

JS

var theDiv = document.getElementsByClassName("manyDivs");
for(var i = 0; i < theDiv.length; i++) {
    theDiv[i].style.display = "none";
}
function run(){
    var theDiv = document.getElementsByClassName("manyDivs");
    for(var i = 0; i < theDiv.length; i++) {
        var randomNum = Math.floor(Math.random() * theDiv.length);
        randomNum[i].style.display = "block";
    }
 }

You appear to have declared theDiv twice and it’s possible this is causing an issue. Just declare it once and see if that helps.

well I did it twice so I could hide the divs first and then click on the button and the get only one div randomly but is just not working, somebody else commented "randomNum is a number, you can’t do randomNum[i]" but I dont know why I cant use randomNum ?

sorry I was using the wrong codepen

So this is correct. Using [i] means you want the ith element of an array or string, however randomNum is an integer, on which this selection operator does not work. I assume randomNum is supposed to be the index of theDiv, and so you would actually want theDiv[randomNum] instead to ensure it’s selecting the correct element.

1 Like

Just wanted to make a follow up post after some testing. Firstly, as I mentioned before you don’t need to declare theDiv twice, if you just keep the first declaration and remove the one inside of the function this will work exactly the same way as you do not need to declare the same variable with the var keyword twice.

Secondly, I think your main problem is with the function itself. You are running a for loop and then wanting to use randomNum as an index, however using the for loop means that the code is run 4 different times. As such, you could end up with 2, 3 or occasionally all 4 divs being unhidden with one click. I’m not sure if this is your intention but it’s something to watch out for.