JS & jQuery can’t detect html elements, and say’s they are undefined

Because your script tag is above the HTML defining the elements that it acts on, it can’t find them because they don’t exist as of when that code runs. Here’s the order in which things are happening in your page:

  1. The html and head elements are created
  2. The meta element is created and its content noted by the parser
  3. The script element for jQuery is created
  4. The parser stops and waits for the jQuery file to load
  5. Once loaded, the jQuery file is executed
  6. Parsing continues
  7. The script element for your code is created
  8. The parser stops and waits for your file to load
  9. Once loaded, your script code is run — and doesn’t find any elements, because there are no div elements yet
  10. Parsing continues
  11. The browser finishes parsing and building the page, which includes creating the elements you’re trying to access in your script

Ways to correct it:

  1. Move the script elements to the very end, just before the closing </body> tag, so all of the elements exist before your code runs. Barring a good reason not to do this, this is usually the best solution.

  2. Use jQuery’s ready feature.

  3. Use the defer attribute on the script element, but beware that not all browsers support it yet.

But again, if you control where the script elements go, #1 is usually your best bet.

Leave a Comment