1

How do I pull a string randomly from an array, and insert that string into a span? Heres the arrays:

var startupX = ['Uber', 'Google', 'Amazon', 'Apple', 'Facebook', 'Twitter'];
var startupY = ['Slack', 'Trello', 'Tesla', 'Hyperloop', 'Harvest'];

And these are the spans that a startup name needs to go into

<h1 id="xForY"></h1>
  <h1>A startup that is 
    <span id="startupX"></span>, but for 
    <span id="startupY"></span>
    </h1>
2
  • Which part are you having trouble with? Is it just the random part, or do you not know how to insert any text into a span using JS? Commented Jul 5, 2016 at 23:35
  • You can get your answer here: stackoverflow.com/questions/4550505/… Commented Jul 6, 2016 at 0:33

2 Answers 2

1

First, find a random element from each of the arrays. Math.random() will help you with that.

Then you can use the DOM API to insert it into your page:

var startupX = ['Uber', 'Google', 'Amazon', 'Apple', 'Facebook', 'Twitter'];
var startupY = ['Slack', 'Trello', 'Tesla', 'Hyperloop', 'Harvest'];

var x = startupX[Math.floor(Math.random()*startupX.length)];
var y = startupY[Math.floor(Math.random()*startupY.length)];

document.getElementById('startupX').innerHTML = x;
document.getElementById('startupY').innerHTML = y;  
<h1 id="xForY"></h1>
<h1>A startup that is 
    <span id="startupX"></span>, but for 
    <span id="startupY"></span>
</h1>

Sign up to request clarification or add additional context in comments.

2 Comments

This is great, to try and understand how it works tho-- innerHTML = x is taking the result of var x and replacing "startupX"?
@OwenSchifferli It sets the inner HTML of the element with id startupX to the content of variable x.
1

Math.random will give you a number from 0 inclusive to 1 exclusive [0, 1).

You can use that to get a random number that is within the max array index:

var randomIndex = Math.floor(Math.random() * startupX.length);

Then you can use this index to access your array:

startupX[randomIndex];

Having the value you can place it on the element:

document.getElementById('startupX').innerHTML = startupX[randomIndex];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.