document.getElementById
, $("#id")
or any other DOM method/jQuery selector cannot find the element?
Example questions include:
.val()
, .html()
, .text()
) return undefined
null
result in the following error: Uncaught TypeError: Cannot set null property '...'
Uncaught TypeError: Cannot set property on null (setting '...')
Uncaught TypeError: Cannot read property '...' of null
Uncaught TypeError: Cannot read property of null (read '...')
The most common form is:
Uncaught TypeError: Cannot set property 'onclick' to null
Uncaught TypeError: Cannot read property 'addEventListener' of null
Uncaught TypeError: Cannot read property 'style' of null
P粉9389363042023-10-16 00:42:10
Short: Because the element you are looking for does not exist in the document yet.
For the rest of this answer I will use for example getElementById
, but the same applies to getElementsByTagName
, < code>querySelector, and any other DOM method that selects elements.
possible reason
Three reasons why the element may not exist:
The element with the passed ID does not exist in the document. You should double check that the ID you pass to getElementById
actually matches the ID of an existing element in the (generated) HTML, and that you didn't misspell the ID (IDs are case sensitive!).
If you use getElementById
, make sure you only provide the ID of the element (e.g. document.getElemntById("the-id ")
). If you are using a method that accepts a CSS selector (for example, querySelector
), be sure to include # before the ID to indicate that you are looking for the ID (for example,
document.querySelector(" #the-id")
). You can not use # with
getElementById
and must use it with querySelector
and similar of. Also note that an id attribute containing .
characters is bad if the ID is contained within a CSS identifier
(e.g. .
) (but works), you have to escape these when using querySelector
(document.querySelector("#the\\.id")
)) , but use getElementById
( >document.getElementById("the.id")
).
The element did not exist when you called getElementById
.
Even though you can see the element on the page, the element is not in the document you are querying because it is in an iframe
(which is its own document). When you search for documents that contain elements in iframe
, these elements are not searched.
If the problem is cause 3 (located in an iframe
or similar file), you need to look at the document in the iframe
rather than the parent document, perhaps by getting the iframe
element and use its < code>contentDocument attribute to access its document (same origin only). The remainder of this answer addresses the first two reasons.
The second reason - that it hasn't appeared yet - is common. Browsers parse and process HTML from top to bottom. This means that any calls to the DOM element that occur before the DOM element appears in the HTML will fail.
Consider the following example:
sssccc
div
appears after
script. When the script is executed, the element does not yet exist and getElementById
will return null
.
jQuery
The same applies to all jQuery selectors. If you misspell your selectors, or if you try to select them before they actually exist, jQuery won't find them.
An additional problem is when jQuery is not found because you loaded the script without a protocol and are running it from the file system:
ssscccThis syntax is used to allow scripts to be loaded over HTTPS on pages with protocol https:// and the HTTP version on pages with protocol http://
It has the unfortunate side effect of trying to load
file://somecdn.somewhere.com... but failing
solution
Before callinggetElementById (or any DOM method for that matter), make sure that the element you want to access exists, i.e. the DOM is loaded.
after the corresponding DOM element
ssscccIn this case, you can also place the code before the closing body tag (
) (all DOM elements will be available when executing the script).
Other solutions include listening for
load
[MDN] or DOMContentLoaded
[MDN] events. In these cases, it doesn't matter where in the document you place the JavaScript code, just remember to place all DOM handling code in event handlers.
Example:
window.onload = function() { // process DOM elements here }; // or // does not work IE 8 and below document.addEventListener('DOMContentLoaded', function() { // process DOM elements here });
See the article
on quirksmode.org for more information on event handling and browser differences.
jQuery
First make sure jQuery is loaded correctly.
Use your browser's developer tools Find out if the jQuery file is found and correct the URL if not (e.g. add http: or
https: scheme at the beginning, Adjust path, etc.)
Listening
load/
DOMContentLoaded The event is exactly what jQuery uses
.ready()
[Documentation]. All jQuery code that affects DOM elements should be inside this event handler.
In fact, the
jQuery tutorial clearly states:
// do stuff when DOM is ready });
Alternatively, you can use the shorthand syntax:
$(function() { // do stuff when DOM is ready });
The two are equivalent.
P粉1229324662023-10-16 00:14:24
The element you are trying to find is not in the DOM< /a> when your script runs.
The location of a script that relies on the DOM can have a profound impact on its behavior. Browsers parse HTML documents from top to bottom. Elements are added to the DOM, and scripts are (usually) executed when they are encountered. This means the order matters. Typically, scripts cannot find elements that appear later in the markup because these elements have not yet been added to the DOM.
Consider the following tags; Script #1 cannot find sssccc