search

Home  >  Q&A  >  body text

Why can't jQuery or getElementById locate the element?

What are the possible reasons why

document.getElementById, $("#id") or any other DOM method/jQuery selector cannot find the element?

Example questions include:

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 'addEventList ener' of null

Uncaught TypeError: Cannot read property 'style' of null


P粉575055974P粉575055974400 days ago737

reply all(2)I'll reply

  • P粉976737101

    P粉9767371012023-10-16 13:56:39

    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:

    1. 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")).

    2. The element did not exist when you called getElementById.

    3. 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:

    sssccc

    This 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 calling

    getElementById (or any DOM method for that matter), make sure that the element you want to access exists, i.e. the DOM is loaded.

    This can be ensured by simply placing the JavaScript

    after the corresponding DOM element

    sssccc

    In 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.

    reply
    0
  • P粉275883973
  • Cancelreply