[Solved] Select random element and set attribute background color [closed]


When you use class instead of id then you can do something like this.

  • Get all the hello elements
  • Create a random Index in the range from zero to the length of your elements
  • Set the style.color of this random Index element in your helloElements to red
let helloElements = document.querySelectorAll(".hello");


let ind = (Math.floor(Math.random() * helloElements.length))
console.log(ind);
helloElements[ind].style.color = "red";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 class="hello">a</h1> <h1 class="hello">b</h1> <h1 class="hello">c</h1>

solved Select random element and set attribute background color [closed]