0

Im trying to make a script to select a random element and change the css elements of it. They all have id's but are all the same as I used a function to make them.

const display = document.getElementsByClassName('display')[0];
function grid() {
    for(let i = 0; i < 6; i++) {
        for(let j = 0; j < 4; j++) {
             square = document.createElement('div');
            square.className = 'square';
            display.appendChild(square);
        }
    }
};

grid();

Above is the function I use to make the elements but I dont know how to make it so I can randomly select one of them.

Bmoney
  • 11
  • 1

2 Answers2

0

Get a list of all your elements, which you can either do as part of grid():

function grid() {
  const elements = [];
  for(..) {
    for(...) {
      const square = ...
      ...
      elements.push(square);
    }
  }
  return elements;
}

const squares = grid();

or you can just query-select them:

...
grid();
const squares = Array.from(document.querySelectorAll(`.square`);

After which "getting a random one" already has Getting a random value from a JavaScript array as established answered post.

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
0

With plain JavaScript:

Plain JavaScript can seem a bit wordy/complicated to read through, but it's self-contained, so it's the best choice for developers with an aversion to using libraries.

var squares = document.querySelectorAll(".square");
squares[Math.floor(Math.random() * squares.length)].style.background = "red";
.square{
  display:inline-block;
  width:50px;
  height:50px;
  background:blue;
}
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>

With Rando.js:

Rando.js makes the randomness simpler to read while also increasing the entropy of the randomness (so people can't predict what the next "random" result will be).

rando(document.querySelectorAll(".square")).value.style.background = "red";
.square{
  display:inline-block;
  width:50px;
  height:50px;
  background:blue;
}
<script src="https://randojs.com/2.0.0.js"></script>

<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>

With both Rando.js and jQuery (what I would do)

Rando.js handles the randomness while jQuery makes element selection and style editing simpler to read.

rando($(".square")).value.css({background: "red"});
.square{
  display:inline-block;
  width:50px;
  height:50px;
  background:blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://randojs.com/2.0.0.js"></script>

<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15