Why can't jQuery or DOM methods like getElementById locate elements?
P粉720716934
P粉720716934 2023-10-15 15:40:06
0
2
530
What are the possible reasons why

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

Example questions include:

  • jQuery silently fails to bind event handlers
  • jQuery "getter" methods (.val(),.html(),.text()) returnundefined
  • Standard DOM methods that returnnullresult 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粉720716934
P粉720716934

reply all (2)
P粉938936304

Short:Because the element you are looking for does not exist in the document yet.


For the rest of this answer I will usefor examplegetElementById, but the same applies togetElementsByTagName,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 togetElementByIdactually matches the ID of an existing element in the (generated) HTML, and that you didn't misspell the ID (IDs arecase sensitive!).

    If you usegetElementById, make sure youonlyprovide 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 cannotuse# withgetElementByIdandmustuse it withquerySelectorand similar of. Also note that anidattribute containing.characters is bad if the ID is contained within aCSS identifier(e.g..) (but works), you have to escape these when usingquerySelector(document.querySelector("#the\\.id"))) , but usegetElementById(>document.getElementById("the.id")).

  2. The element did not exist when you calledgetElementById.

  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 aniframe(which is its own document). When you search for documents that contain elements iniframe, these elements are not searched.

If the problem is cause 3 (located in aniframeor similar file), you need to look at the document in theiframerather than the parent document, perhaps by getting theiframeelement and use itscontentDocumentattribute 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
           

divappearsafterscript. When the script is executed, the element does not yet exist andgetElementByIdwill returnnull.

jQuery

The same applies to all jQuery selectors. If youmisspellyour selectors, or if youtry 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 thecorresponding DOM element

           
sssccc
In this case, you can also place the code before the closing body tag (

    P粉122932466

    The element you are trying to find is not in theDOM 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

    , while Script #2 succeeds:

    sssccc
                   
    test div
    sssccc

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!