Daiaiai
Daiaiai

Reputation: 1089

Randomize insertion in for-loop

I'd like to randomize my HTML-output with multiple elements within my for-loop:

var h = document.getElementById("test_block");
for(i = 0; i < 7; i++) {
  h.insertAdjacentHTML("afterend", "<div class='one_hour onesy'><p>Foo</p></div>");
}

With a random output within the forloop of:

<div class='one_hour onesy'><p>Foo</p></div>
<div class='two_hour onesy'><p>Loo</p></div>
<div class='three_hour onesy'><p>Too</p></div>

So I'd like to get the adjacented HTML to be randomly one of these lines. How can I do that?

Upvotes: 0

Views: 60

Answers (1)

axl-code
axl-code

Reputation: 2274

Lets see if this helps:

var results = [
  '<div class="one_hour onesy"><p>Foo</p></div>',
  '<div class="two_hour onesy"><p>Foo</p></div>',
  'whatever',
  ...
];

for(i = 0; i < 7; i++) {
  h.insertAdjacentHTML("afterend", results[Math.floor((Math.random() * results.length))]);
}

Upvotes: 2

Related Questions