Uncaught TypeError: Cannot read property 'appendChild' of null

后端 未结 10 1972
予麋鹿
予麋鹿 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 08:52

    There isn't an element on your page with the id "mainContent" when your callback is being executed.

    In the line:

    document.getElementById("mainContent").appendChild(p);
    

    the section document.getElementById("mainContent") is returning null

    0 讨论(0)
  • 2020-12-14 08:54

    If this is happening to you in an AJAX post, you'll want to compare the values that you're sending and the values that the Controller is expecting.

    In my case, I had changed a parameter in a serializable class from State to StateID, and then in an AJAX call didn't change the receiving field out 'data'

    success: function (data) { MakeAddressForm.formData.StateID = data.State;

    Note that the class was changed - it doesn't matter what I call it in the formData.

    This created a null reference in the formData which I was trying to post back to the Controller once I'd done the update. Obviously, if someone changed the state (which was the purpose of the form) then they didn't get the error, so it made for a hard one to find.

    This also through a 500 error. I'm posting this here in hopes it saves someone else the time I've wasted

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

    Instead of using your script tag defining the source of your .js file in <head>, place it at the bottom of your HTML code.

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

    Use querySelector insted of getElementById();

    var c = document.querySelector('#mainContent');
        c.appendChild(document.createElement('div'));
    
    0 讨论(0)
  • 2020-12-14 09:06

    add your script tag on the bottom of the body tag. so that script loads after html content then you won't get such error and add=

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

    Nice answers here. I encountered the same problem, but I tried <script src="script.js" defer></script> but I didn't work quite well. I had all the code and links set up fine. The problem is I had put the js file link in the head of the page, so it was loaded before the DOM was loaded. There are 2 solutions to this.

    1. Use
    window.onload = () => {
        //write your code here
    }
    
    1. Add the <script src="script.js"></script> to the bottom of the html file so that it loads last.
    0 讨论(0)
提交回复
热议问题