HTML, JS, receiving Uncaught TypeError: Cannot set property 'innerHTML' of null when variable has value

HTML, JS, receiving Uncaught TypeError: Cannot set property 'innerHTML' of null when variable has value

Situation

我有一个HTML,我想在每次重新加载时显示一个随机单词。

Problem

我有以下 HTML:

<h1 style="font-family: 'Oswald', ;">Alex is currently: <span style="color: rgba(25, 114, 120, 1);" id="status">Alive</span></h1>

我想将 status 的值更改为 alive 以外的随机词。我将这些变量存储在一个数组中,并且我有一个运行 onload():

的函数
function changeStatus() {
   let statuses = ['Existing', 'Vibing'];
   let finalStatus = statuses[Math.floor(Math.random() * statuses.length)];
   document.getElementById('user').innerHTML = finalStatus;
}

Error

然而,当我重新加载我的页面时,控制台中出现以下错误:

Uncaught TypeError: Cannot set property 'innerHTML' of null

Ideal outcome

我想知道我做错了什么以及如何解决它,最好只使用 Javascript,但如果需要我可以使用 jQuery。

您正在访问一个不存在的 ID user。可能你想要

document.GetElementById('status')

没有 ID 为 'user' 的元素。

替换

document.getElementById('user').innerHTML = finalStatus;

document.getElementById('status').innerHTML = finalStatus;

user更改为status

function changeStatus() {
   let statuses = ['Existing', 'Vibing'];
   let finalStatus = statuses[Math.floor(Math.random() * statuses.length)];
   document.getElementById('status').innerHTML = finalStatus;
}

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>

要获取状态元素,您需要使用 id,它是 'status' 而不是 user

var _ele= document.getElementById('status');

_ele.innerHTML = 最终状态;