已声明元素id仍触发Cannot read property innerHTML of null错误求助
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
idis exactlygetFavMovie(no extra spaces, capitalization differences, or typos likegetFavMoviesorgetfavmovie—IDs are case-sensitive!) - There’s only one element with that ID in your HTML.
getElementByIdwill 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

