0

I'm at a complete loss as to how to get my code working correctly. I've looked at so many other forums and questions, but have yet to get it functioning. As the title suggests, it always goes with the second if statement no matter what. What I'm trying to do is get a random variable (either 1 or 2) and use that to decide which of two divs with the same class to display. I have them defaulting to display:none and having the variable change them to display: block because the divs are shown based on geolocation and if there are two instead of one, I only want one to show but be randomly picked. Here's the code I'm trying to get working:

window.onload = function() {
  function randomNumber(min, max) { 
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
  var randintvar=randomNumber(1,2);
    if (randintvar == 1) {
          document.querySelector(".variable-div").style.display = "none";
          document.querySelector(".variable-div:first-child").style.display = "block";
     }
    if (randintvar == 2) {
          document.querySelector(".variable-div").style.display = "none";
          document.querySelector(".variable-div:last-child").style.display = "block";
     }
}
<div class="variable-div">
First Div
</div>

<div class="variable-div">
Second Div
</div>

I did get this to work properly:

window.onload = function() {
  function randomNumber(min, max) { 
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
var randintvar=randomNumber(1,2);
alert(randintvar);
}

That ended up working to show an alert and is able to randomly show one of two integers, so it has something to do with my "if" statements. I've been banging my head trying to figure it out. Help save me please!

Appreciate any input. Thank you!

  • From your snippet, no elements match `.variable-div:last-child` (due to the ` – CertainPerformance Apr 11 '21 at 20:39
  • The duplicate close is not very helpful... The issue is that you have your `div`s in the `body` where other scripts (such as browser extensions or in this case part of SO's preview code) will insert other elements too. Therefore, the last child of the body is likely going to be something else so no element will match `.variable-div:last-child` because the `:last-child` won't match `.variable-div` then. Instead, try giving them different classes and selecting those. Also, the first line (to hide them) won't work as intended either, because it will affect only the first one (this isn't jQuery). – CherryDT Apr 11 '21 at 20:45
  • So it doesn't go with the second statement no matter what, it's just that your code doesn't do what you think it does. The best way to see what's actually happening would be by using the browser devtools to single-step through each line of your code. – CherryDT Apr 11 '21 at 20:47

0 Answers0