1

This is driving me crazy. I have a HTML page with a form element as shown below:

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  <script src="formHandler.js"></script>
  <script src="app.js"></script>

</head>

<body>

  <form data-coffee-order="form">
    <input type="submit" />
  </form>

</body>

In my app.js I try to access the form element using the querySelector as shown below:

var FORM_SELECTOR = '[data-coffee-order="form"]'

var form = document.querySelector(FORM_SELECTOR)
console.log(form) // this is null why? 

For some reason form is always null. Why is that?

john doe
  • 9,220
  • 23
  • 91
  • 167
  • Are you adding in the `data-coffee-order="form"` in afterwards (Perhaps doing jQuery `.data()`)? – Blue Apr 26 '17 at 17:23

1 Answers1

3

Because the JavaScript code is executing before the element actually exists. Place the code after:

<body>

    <form data-coffee-order="form">
        <input type="submit" />
    </form>

    <script src="app.js"></script>

</body>

(This may also apply to your other JavaScript. It's not necessary, but even if just for consistency it would make sense. Unless there's JavaScript code you want to be executed immediately, before the DOM is loaded.)

David
  • 208,112
  • 36
  • 198
  • 279