Why does jQuery or a DOM method such as getElementById not find the element?

What are the possible reasons for document.getElementById , $("#id") or any other DOM method / jQuery selector not finding the elements?

Example problems include:

jQuery silently failing to bind an event handler, and a standard DOM method returning null resulting in the error:

Uncaught TypeError: Cannot set property '...' of null


The element you were trying to find wasn't in the DOM when your script ran.

The position of your DOM-reliant script can have a profound effect upon its behavior. Browsers parse HTML documents from top to bottom. Elements are added to the DOM and scripts are (generally) executed as they're encountered. This means that order matters. Typically, scripts can't find elements which appear later in the markup because those elements have yet to be added to the DOM.

Consider the following markup; script #1 fails to find the <div> while script #2 succeeds:

<script>
  console.log("script #1: %o", document.getElementById("test")); // null
</script>
<div id="test">test div</div>
<script>
  console.log("script #2: %o", document.getElementById("test")); // <div id="test" ...
</script>

Short and simple: Because the elements you are looking for do not exist in the document (yet).


For the remainder of this answer I will use getElementById as example, but the same applies to getElementsByTagName , querySelector and any other DOM method that selects elements.

Possible Reasons

There are two reasons why an element might not exist:

  • An element with the passed ID really does not exist in the document. You should double check that the ID you pass to getElementById really matches an ID of an existing element in the (generated) HTML and that you have not misspelled the ID (IDs are case-sensitive!).

    Incidentally, in the majority of contemporary browsers, which implement querySelector() and querySelectorAll() methods, CSS-style notation is used to retrieve an element by its id , for example: document.querySelector('#elementID') , as opposed to the method by which an element is retrieved by its id under document.getElementById('elementID') ; in the first the # character is essential, in the second it would lead to the element not being retrieved.

  • The element does not exist at the moment you call getElementById .

  • The latter case is quite common. Browsers parse and process the HTML from top to bottom. That means that any call to a DOM element which occurs before that DOM element appears in the HTML, will fail.

    Consider the following example:

    <script>
        var element = document.getElementById('my_element');
    </script>
    
    <div id="my_element"></div>
    

    The div appears after the script . At the moment the script is executed, the element does not exist yet and getElementById will return null .

    jQuery

    The same applies to all selectors with jQuery. jQuery won't find elements if you misspelled your selector or you are trying to select them before they actually exist.

    An added twist is when jQuery is not found because you have loaded the script without protocol and are running from file system:

    <script src="//somecdn.somewhere.com/jquery.min.js"></script>
    

    this syntax is used to allow the script to load via HTTPS on a page with protocol https:// and to load the HTTP version on a page with protocol http://

    It has the unfortunate side effect of attempting and failing to load file://somecdn.somewhere.com...


    Solutions

    Before you make a call to getElementById (or any DOM method for that matter), make sure the elements you want to access exist, ie the DOM is loaded.

    This can be ensured by simply putting your JavaScript after the corresponding DOM element

    <div id="my_element"></div>
    
    <script>
        var element = document.getElementById('my_element');
    </script>
    

    in which case you can also put the code just before the closing body tag ( </body> ) (all DOM elements will be available at the time the script is executed).

    Other solutions include listening to the load [MDN] or DOMContentLoaded [MDN] events. In these cases it does not matter where in the document you place the JavaScript code, you just have to remember to put all DOM processing code in the 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
    });
    

    Please see the articles at quirksmode.org for more information regarding event handling and browser differences.

    jQuery

    First make sure that jQuery is loaded properly. Use the browser's developer tools to find out whether the jQuery file was found and correct the URL if it wasn't (eg add the http: or https: scheme at the beginning, adjust the path, etc.)

    Listening to the load / DOMContentLoaded events is exactly what jQuery is doing with .ready() [docs]. All your jQuery code that affects DOM element should be inside that event handler.

    In fact, the jQuery tutorial explicitly states:

    As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.

    To do this, we register a ready event for the document.

    $(document).ready(function() {
       // do stuff when DOM is ready
    });
    

    Alternatively you can also use the shorthand syntax:

    $(function() {
        // do stuff when DOM is ready
    });
    

    Both are equivalent.


    Reasons why id based selectors don't work

  • The element/DOM with id specified doesn't exist yet.
  • The element exists, but it is not registered in DOM [in case of HTML nodes appended dynamically from Ajax responses].
  • More than one element with the same id is present which is causing a conflict.
  • Solutions

  • Try to access the element after its declaration or alternatively use stuff like $(document).ready();

  • For elements coming from Ajax responses, use the .bind() method of jQuery. Older versions of jQuery had .live() for the same.

  • Use tools [for example, webdeveloper plugin for browsers] to find duplicate ids and remove them.

  • 链接地址: http://www.djcxy.com/p/55788.html

    上一篇: jquery checked复选框IE问题

    下一篇: 为什么jQuery或像getElementById这样的DOM方法找不到元素?