简体   繁体   中英

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

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

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM