Uncaught TypeError: Cannot read property 'appendChild' of null

后端 未结 10 1973
予麋鹿
予麋鹿 2020-12-14 08:43

I\'m getting the following error

Uncaught TypeError: Cannot read property \'appendChild\' of null

myRequest.onreadystatechange @ script.js

相关标签:
10条回答
  • 2020-12-14 09:09

    put your javascript at the bottom of the page (ie after the element getting defined..)

    0 讨论(0)
  • 2020-12-14 09:10

    You can load your External JS files in Angular and you can load them directly instead of defining in index.html file.

    component.ts:

    ngOnInit() {
        this.loadScripts();
    }
    
    
      loadScripts() {
        const dynamicScripts = [
          //scripts to be loaded
          "assets/lib/js/hand-1.3.8.js",
          "assets/lib/js/modernizr.jr.js",
          "assets/lib/js/jquery-2.2.3.js",
          "assets/lib/js/jquery-migrate-1.4.1.js",
          "assets/js/jr.utils.js"
        ];
        for (let i = 0; i < dynamicScripts.length; i++) {
          const node = document.createElement('script');
          node.src = dynamicScripts[i];
          node.type = 'text/javascript';
          node.async = false;
          document.getElementById('scripts').appendChild(node);
        }
      }
    

    component.html:

    <div id="scripts">
    </div>
    

    You can also load styles similarly.

    component.ts:

    ngOnInit() {
        this.loadStyles();
    }
    
    
      loadStyles() {
        const dynamicStyles = [
          //styles to be loaded
          "assets/lib/css/ui.css",
          "assets/lib/css/material-theme.css",
          "assets/lib/css/custom-style.css"
        ];
        for (let i = 0; i < dynamicStyles.length; i++) {
          const node = document.createElement('link');
          node.href = dynamicStyles[i];
          node.rel = 'stylesheet';
          document.getElementById('styles').appendChild(node);
        }
      }
    

    component.html:

    <div id="styles">
    </div>
    
    0 讨论(0)
  • 2020-12-14 09:11

    For people who have the same issue of querySelector or getElementById that returns the following error:

    Uncaught TypeError: Cannot read property 'appendChild' of null
    

    but you have a class name or id in the HTML...

    If your script tag is in the head, the JavaScript is loaded before your HTML. You will need to add defer to your script like so:

    <script src="script.js" defer></script>
    
    0 讨论(0)
  • 2020-12-14 09:14

    those getting querySelector or getElementById that returns the following error:

    Uncaught TypeError: Cannot read property 'appendChild' of null
    

    or any other property, even if you have a class name or id in the HTML

    don't use (defer as it is too much browser dependent.)

    <script src="script.js" defer></script>  //don't use this
    

    instead, put all your code in 'script.js' inside

    $(document).ready(function(){
        //your script here.
    }
    
    0 讨论(0)
提交回复
热议问题