Reputation: 1245
Situation
I have a HTML which I would like to display a random word every time it is reloaded.
Problem
I have the following HTML:
<h1 style="font-family: 'Oswald', ;">Alex is currently: <span style="color: rgba(25, 114, 120, 1);" id="status">Alive</span></h1>
I would like to change the value of status
to random word other than alive. I have these variables stored in an array and I have a function that runs onload()
:
function changeStatus() {
let statuses = ['Existing', 'Vibing'];
let finalStatus = statuses[Math.floor(Math.random() * statuses.length)];
document.getElementById('user').innerHTML = finalStatus;
}
Error
However when I reload my page the following error appears in the console:
Uncaught TypeError: Cannot set property 'innerHTML' of null
Ideal outcome
I would like to know what I am doing wrong and how to fix it, ideally using just Javascript but I can use jQuery if necessary.
Upvotes: 0
Views: 64
Reputation: 42
To get status element, you need to use id which is 'status' not user
var _ele= document.getElementById('status');
_ele.innerHTML = finalStatus;
Upvotes: 1
Reputation: 553
function changeStatus() {
let statuses = ['Existing', 'Vibing'];
let finalStatus = statuses[Math.floor(Math.random() * statuses.length)];
document.getElementById('status').innerHTML = finalStatus;
}
<h1 style="font-family: 'Oswald', ;">Alex is currently: <span style="color: rgba(25, 114, 120, 1);" id="status">Alive</span></h1>
<button onclick="changeStatus()">Change Status</button>
Upvotes: 2
Reputation: 1589
change user
to status
function changeStatus() {
let statuses = ['Existing', 'Vibing'];
let finalStatus = statuses[Math.floor(Math.random() * statuses.length)];
document.getElementById('status').innerHTML = finalStatus;
}
Upvotes: 1
Reputation: 1162
There is no element with id 'user'.
Replace
document.getElementById('user').innerHTML = finalStatus;
With
document.getElementById('status').innerHTML = finalStatus;
Upvotes: 2
Reputation: 1471
You are accessing an id user
that does not exist. Probably you wanted to have
document.GetElementById('status')
Upvotes: 2