document.querySelector(…) is null error

前端 未结 3 1283
傲寒
傲寒 2020-11-30 04:39

For image upload in a cakephp project I used java-script.I added this js file in app\\View\\Layouts default.ctp

js code

document.querySelector(\'in         


        
相关标签:
3条回答
  • 2020-11-30 05:01

    To make sure that your DOM is ready you could add this to your JS file.

    // my-script.js
    document.addEventListener("DOMContentLoaded", function() { 
        // this function runs when the DOM is ready, i.e. when the document has been parsed
        document.querySelector('input[type=file]')
            .addEventListener('change', function(event){
                ...
             }
    });
    

    This way you could call your js files from wherever you like. Please take a look to this superb answer to get further insight on these matters.

    Also take a look at this other Google rule.

    0 讨论(0)
  • 2020-11-30 05:13

    I suggest writing your <script type="text/javascript" src="your js file"></script> in body, before the closing tag

    0 讨论(0)
  • 2020-11-30 05:16

    document.querySelector() behaves similarly to the jQuery.(document).ready() method. When the DOM is ready, the selector returns the object.

    I would suggest you call all JS script bottom of the page.

    0 讨论(0)
提交回复
热议问题