Skip to content Skip to sidebar Skip to footer

Display Random Div From X Divs Selected By CSS-Class

I have, on a homepage, X html div elements in one page, with X different classnames: class='home-1' class='home-2' class='home-3' class='home-4' etc. My goal is, to dislpay o

Solution 1:

Use Math.random() and seed it with the number of elements you have:

let els = document.querySelectorAll(".home")

let num = Math.floor(Math.random() * els.length)

els[num].style.display = "inline-block"
.home{display: none; padding: 15px}

.home-1{background-color: lightblue}
.home-2{background-color: yellow}
.home-3{background-color: pink}
.home-4{background-color: seagreen;color:#fff}
<div class="home home-1">1</div>
<div class="home home-2">2</div>
<div class="home home-3">3</div>
<div class="home home-4">4</div>

Solution 2:

You can find the class randomly, then hide all except the element with the random class:

var classList = Array.from(document.querySelectorAll('[class^=home-]')).map(el => el.className);
var random = classList[Math.floor(Math.random() * classList.length)];
document.querySelectorAll(`[class^=home-]:not(.${random})`).forEach(el => el.style.display = 'none');
<div class="home-1">home-1</div>
<div class="home-2">home-2</div>
<div class="home-3">home-3</div>
<div class="home-4">home-4</div>
<div class="home-5">home-5</div>

Solution 3:

This snippet won't run on stackoverflow because you aren't allowed to access the local storage. But it should work fine in your environment.

const elements = document.querySelectorAll('div[class^=home-]');
const lastIndex = Number(localStorage.getItem('lastElement'));
let randomIndex = lastIndex;

do {
  randomIndex = Math.floor(Math.random() * elements.length);
} while (randomIndex === lastIndex);

const randomElement = elements[randomIndex];
randomElement.style.display = 'block';

localStorage.setItem('lastElement', randomIndex);
div[class^=home-] {
  display: none;
}
<div class="home-1">home-1</div>
<div class="home-2">home-2</div>
<div class="home-3">home-3</div>
<div class="home-4">home-4</div>
<div class="home-5">home-5</div>

Solution 4:

You can find all div elements that start with the class name 'home-', then generate a random number between 0 and X and check localStorage or sessionStorage for the last saved div number and keep generating numbers if the new random number was the previous.

See below (The script will not run because localStorage won't work here - on SO):

function randomize() {
  let divs = document.querySelectorAll('div[class^="home"]');
  let length = divs.length;
  let currDiv = localStorage.getItem("divActive");
  
  rand = getNextRndm(currDiv, length);
  
  for(var i=0; i<length; i++) {
    if(i != rand) {
      divs[i].style.display = "none";
    } else {
      divs[i].style.display = "block";
      localStorage.setItem("divActive", rand);
    }
  }
}

function getNextRndm(currDiv, length) {
  let rand = Math.floor(Math.random() * length);

  if(currDiv !== null) {
    while(rand == currDiv)
      rand = Math.floor(Math.random() * length);
  }
  return rand;
}

randomize();
<div class="home-1">1st div</div>
<div class="home-2">2nd div</div>
<div class="home-3">3rd div</div>
<div class="home-4">4th div</div>

Post a Comment for "Display Random Div From X Divs Selected By CSS-Class"