How just to show one random div from my array?

Hello I was wondering how to randomly display only one div randomly instead of the three divs at the same time from my array with the const data
CODEPEN
html

<div id="myData"></div>

css

.divStyle1 {
    display: inline-block;
    color: #000;
    background: pink;
    margin: 10px;
    padding: 20px 30px; 
  }
  
  .divStyle2 {
    display: inline-block;
    color: #000;
    background: red;
    margin: 10px;
    padding: 20px 30px;
  }
  
  .divStyle3 {
    display: inline-block;
    color: #000;  
    background: green;
    margin: 10px;
    padding: 20px 30px;
  }

js

const data = [
    {
      "firstDiv": "Hello this is the first div",
      "secondtDiv": "Hello this is the second div",
      "thirdtDiv": "Hello this is the third div" 
    }
]

function appendData(data) {
        var mainContainer = document.getElementById("myData");
        for (var i = 0; i < data.length; i++) {
            var random = Math.floor(Math.random()*data.length);
            var div = document.createElement("div");
            div.innerHTML = '<span class="divStyle1">' + data[i].firstDiv + '</span>' + 
            '<span class="divStyle2">' + data[i].secondtDiv + '</span>' +
            '<span class="divStyle3">' + data[i].thirdtDiv + '</span>' ;
            div.src = data[random]
            mainContainer.appendChild(div);
        }
    }
appendData(data);


Why the loop? data[i] is:

{
      "firstDiv": "Hello this is the first div",
      "secondtDiv": "Hello this is the second div",
      "thirdtDiv": "Hello this is the third div" 
    }

So your loop runs once giving you the output you provided.

What do you think this line of code does?
If you want to randomly display one div don’t use a loop and don’t create three span for each.

const data = [
    {
      "firstDiv": "Hello this is the first div",
      "secondtDiv": "Hello this is the second div",
      "thirdtDiv": "Hello this is the third div" 
    }
]

Also, if you change your data variable to something like the following it might be easier to accomplish to access a random one:

const data = [
    {"firstDiv": "Hello this is the first div"},
     {"secondtDiv": "Hello this is the second div"},
     {"thirdtDiv": "Hello this is the third div"} 
    }
]

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.