0

I'm trying to randomly set some css rules to different section tags, but I don't know how many section tags I will end up with. If there are 10 section tags, each section should have a random class name between section0 to section9. It needs to be randomized and not in order.

I read about document.getElementByTagName and I'm able to assign class names with an integer by using a for loop, but I'm not sure where and how to implement Math.floor(Math.random() * myArray.length) and return it correctly.

   function myFunction(){
    var randomize = document.getElementsByTagName("section");
    for (i = 0; i <= randomize.length; i++) {
        randomize[i].className = "section" + i;
        }
    }

I've tried i = Math.floor(Math.random() * randomize.length);

and return randomize[i].className = "section" + i;

but that does not seem to work. I'm trying to incorporate two things I've been reading about but I'm not sure how to correctly do so.

Liam
  • 27,717
  • 28
  • 128
  • 190
kingsman
  • 67
  • 4

1 Answers1

1

This version of a solution randomly generates a number dependent upon how many sections there are. It keeps track of the numbers already used in an array. So long as a number is already used, it will keep trying.

var sections = document.querySelectorAll('section');
var usedValues = [];

[...sections].forEach(function(section){
  var classAssigned = false;
  
  while (!classAssigned) {
    let randomNumber = Math.floor(Math.random() * 100 * sections.length) % sections.length;
    
    if (classAssigned = !usedValues.includes(randomNumber)) {
      section.classList.add('section'+ randomNumber);
      usedValues.push(randomNumber);
    }
  }
});
<section>A</section>
<section>B</section>
<section>C</section>
<section>D</section>
<section>E</section>
<section>F</section>
<section>G</section>
<section>H</section>
<section>I</section>
<section>J</section>
<section>K</section>
<section>L</section>
<section>M</section>
<section>N</section>
Taplar
  • 24,788
  • 4
  • 22
  • 35
  • Thank you very much. You not only showed me a better way to look at this problem, but taught me some shorthand that will go a long way. – kingsman May 31 '19 at 15:22
  • Awesome, :). What shorthand did you take away? Out of curiosity. @kingsman – Taplar May 31 '19 at 15:24