'How can I display an random quote from an Javascript Array in html?

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 class="randomTitle" 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



Solution 1:[1]

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>

Solution 2:[2]

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

Solution 3:[3]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 innocent
Solution 2 diemondtank
Solution 3