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>