You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已声明元素id仍触发Cannot read property innerHTML of null错误求助

Fixing "Uncaught TypeError: cannot read property 'innerHTML' of null" for Your localStorage Movie Code

Hey there! I totally get how frustrating this error is—especially when you’re positive you have that getFavMovie element in your HTML. Let’s break down the most common reasons this happens and how to fix them:

1. Your JavaScript is running before the DOM finishes loading

This is the #1 culprit for this error. If your script tag is placed in the <head> section, or even early in the <body> before the getFavMovie element is rendered, your code will try to access an element that doesn’t exist yet (hence the null).

Fix:

Either move your script to right before the closing </body> tag (so it runs after all elements are loaded), or wrap your code in a DOMContentLoaded listener to make sure it only runs once the DOM is ready:

document.addEventListener('DOMContentLoaded', function() {
  // Get your element safely after DOM is ready
  const favMovieElement = document.getElementById('getFavMovie');
  const savedMovie = localStorage.getItem('favMovie');

  if (savedMovie) {
    favMovieElement.innerHTML = savedMovie;
  } else {
    favMovieElement.innerHTML = 'No movie';
  }
});

2. Check for typos or duplicate IDs

Double-check your HTML to make sure:

  • The element’s id is exactly getFavMovie (no extra spaces, capitalization differences, or typos like getFavMovies or getfavmovie—IDs are case-sensitive!)
  • There’s only one element with that ID in your HTML. getElementById will only return the first matching element, so duplicates can cause unexpected behavior if the first one isn’t the one you’re targeting.

3. Is the element dynamically added?

If you’re generating the getFavMovie element with JavaScript (instead of having it directly in your static HTML), your code might be trying to access it before it’s been added to the DOM.

Fix:

Make sure your code that accesses getFavMovie runs after the code that creates and appends the element to the DOM.

Give these steps a try—chances are one of them will solve your issue!

内容的提问来源于stack exchange,提问作者Philip Carlsson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:10:55