Home > OS >  How can I display an random quote from an Javascript Array in html?
How can I display an random quote from an Javascript Array in html?

Time:05-14

im trying to make random quotes that are listed in an array appear on my website on reload however I cant quite get it to work

Javascript:


function textOfToday() {
    
    var textOfTodayArray = [
        'String 1', 'String 2'
    ]

document.getElementById('randomTitle').value = textOfTodayArray[Math.floor(Math.random()*textOfTodayArray.length)];
}

The following html div code is designed to display the text however I just cant get it:

<div  style="text-align: center;"></div>

Ive also tried using id="randomTitle" in the div part but this did not work either

Is there something else wrong maybe? Im not no expert by all means but I cant spot any syntax mistakes

Any help would be appreciated

CodePudding user response:

You need to use the innerHTML property to display in the HTML element. Also make use of the id tag when you are targeting by Id. Also, You never invoked your function so it never ran.

function textOfToday() {

  var textOfTodayArray = ['String 1', 'String 2'];

  document.getElementById('randomTitle').innerHTML = textOfTodayArray[Math.floor(Math.random() * textOfTodayArray.length)];
}

textOfToday();
<div id="randomTitle" style="text-align: center;">Hi</div>

CodePudding user response:

Make sure to call the function in your js textOfToday(). You are defining it, but never calling.

Also, yes, you need to change the class to id if you are going to use getElementById.

Lastly, you need to set innerText instead of value

CodePudding user response:

document.querySelector('.foo').value mostly using for <input>, to display information in the div or whatever element is it, you better use innerText or innerHTML

function textOfToday() {

var textOfTodayArray = [
    'String 1', 'String 2'
]

document.getElementById('randomTitle').innerText = textOfTodayArray[Math.floor(Math.random()*textOfTodayArray.length)];
}

textOfToday()
<div id="randomTitle" style="text-align: center;"></div>

  • Related