0

I have 12 elements with class "block" and I need to add class "active" to 6 of 12 elements (randomly).

I think using for loop would to the trick but I am not sure how to do it. Maybe somebody can help me out?

for (var i = 0; i < 6; i++) {

    var random = Math.floor(Math.random() * 1000);
    block.eq(random % block.length).addClass("active");

}

This code adds class, but it's not 6 elements every time.. Need a solution to add "active" class to 6 elements every time. Now sometimes it's 6, sometime less..

xoomer
  • 311
  • 2
  • 10
  • 22

1 Answers1

-1

you can select all elements first and by random function chose any six of them and add class active to them

var elements = document.getElementsByName(elementname);

for(var i =0; i<6 ; i++)
 var random = Math.floor((Math.random() * 11) + 1);
 element[random].className += "active";
Azeem112
  • 337
  • 1
  • 8
  • 23
  • but how to do it using jquery? – xoomer Jun 04 '17 at 21:01
  • this code is logically the same as what OP has and it will **_not_** produce **_exactly_** 6 elements every time as `random` might get the same value on 2 different iterations – SergGr Jun 04 '17 at 21:06