简体   繁体   English

无法设置 null 的属性“innerHTML”

[英]Cannot set property 'innerHTML' of null

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?为什么会出现错误或 Uncaught TypeError: Cannot set property 'innerHTML' of null? I thought I understood innerHTML and had it working before.我以为我了解 innerHTML 并且之前可以使用它。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>

<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>

</head>

<body>
<div id="hello"></div>
</body>
</html>

您必须将hello div 放在脚本之前,以便在加载脚本时它存在。

Let us first try to understand the root cause as to why it is happening in first place.让我们首先尝试了解其发生的根本原因。

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?为什么我会收到错误或未捕获的类型错误:无法将属性“innerHTML”设置为 null?

The browser always loads the entire HTML DOM from top to bottom.浏览器总是从上到下加载整个 HTML DOM。 Any JavaScript code written inside the script tags (present in head section of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded.即使在加载整个 DOM(存在于 body 标签中的各种 HTML 元素标签)之前,任何写入script标签(出现在 HTML 文件的head JavaScript 代码都会被浏览器渲染引擎执行。 The scripts present in head tag are trying to access an element having id hello even before it has actually been rendered in the DOM. head标签中的脚本试图访问一个 id hello的元素,甚至在它实际上已经在 DOM 中呈现之前。 So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.很明显,JavaScript 无法看到该元素,因此您最终会看到空引用错误。

How can you make it work as before?你怎么能让它像以前一样工作?

You want to show the "hi" message on the page as soon as the user lands on your page for the first time.您希望在用户第一次登陆您的页面时立即在页面上显示“嗨”消息。 So you need to hook up your code at a point when you are completely sure of the fact that DOM is fully loaded and the hello id element is accessible/available.因此,当您完全确定 DOM 已完全加载并且hello id 元素可访问/可用时,您需要连接代码。 It is achievable in two ways:它可以通过两种方式实现:

  1. Reorder your scripts : This way your scripts get fired only after the DOM containing your hello id element is already loaded.重新排序你的脚本:这样你的脚本只有在包含你的hello id 元素的 DOM 已经加载后才会被触发。 You can achieve it by simply moving the script tag after all the DOM elements ie at the bottom where body tag is ending.您可以通过简单地在所有 DOM 元素之后移动 script 标签来实现它,即在body标签结束的底部。 Since rendering happens from top to bottom so your scripts get executed in the end and you face no error.由于渲染是从上到下进行的,因此您的脚本最终会被执行并且您不会遇到任何错误。

 <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Untitled Document</title> </head> <body> <div id="hello"></div> <script type ="text/javascript"> what(); function what(){ document.getElementById('hello').innerHTML = 'hi'; }; </script> </body> </html>

  1. Use event hooking : Browser's rendering engine provides an event based hook through window.onload event which gives you the hint that browser has finished loading the DOM.使用事件钩子:浏览器的渲染引擎通过window.onload事件提供了一个基于事件的钩子,它给你浏览器已经完成加载 DOM 的提示。 So by the time when this event gets fired, you can be rest assured that your element with hello id already loaded in the DOM and any JavaScript fired thereafter which tries to access this element will not fail.因此,当此事件被触发时,您可以放心,具有hello id 的元素已经加载到 DOM 中,并且此后触发的任何尝试访问此元素的 JavaScript 都不会失败。 So you do something like below code snippet.所以你做一些类似下面的代码片段。 Please note that in this case, your script works even though it is present at the top of your HTML document inside the head tag.请注意,在这种情况下,即使您的脚本位于 HTML 文档顶部head标签内,它也能正常工作

 <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Untitled Document</title> <script type ="text/javascript"> window.onload = function() { what(); function what(){ document.getElementById('hello').innerHTML = 'hi'; }; } </script> </head> <body> <div id="hello"></div> </body> </html>

You could tell javascript to perform the action "onload"... Try with this:您可以告诉 javascript 执行“onload”操作...试试这个:

<script type ="text/javascript">
window.onload = function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>

Just put your JS in window.onload只需将您的 JS 放在window.onload

window.onload = function() {

        what();

        function what() {
            document.getElementById('hello').innerHTML = 'hi';
        };

    }

The JavaScript part needs to run once the page is loaded, therefore it is advised to place JavaScript script at the end of the body tag. JavaScript 部分需要在页面加载后运行,因此建议将 JavaScript 脚本放在 body 标签的末尾。

 <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Example</title> </head> <body> <div id="hello"></div> <script type ="text/javascript"> what(); function what(){ document.getElementById('hello').innerHTML = 'hi'; }; </script> </body> </html>

Javascript looks good. Javascript 看起来不错。 Try to run it after the the div has loaded.尝试在 div 加载后运行它。 Try to run only when the document is ready.尝试仅在文档准备好时运行。 $(document).ready in jquery. $(document).ready在 jquery 中。

 <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Example</title> </head> <body> <div id="hello"></div> <script type ="text/javascript"> what(); function what(){ document.getElementById('hello').innerHTML = '<p>hi</p>'; }; </script> </body> </html>

Here Is my snippet try it.这是我的片段尝试一下。 I hope it will helpfull for u.我希望它对你有帮助。

 <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Untitled Document</title> </head> <body> <div id="hello"></div> <script type ="text/javascript"> what(); function what(){ document.getElementById('hello').innerHTML = 'hi'; }; </script> </body> </html>

您可以尝试使用 setTimeout 方法来确保您的 html 首先加载。

The root cause is: HTML on a page have to loaded before javascript code .根本原因是:页面上的 HTML 必须在 javascript 代码之前加载 Resolving in 2 ways: 2种方式解决:

1) Allow HTML load before the js code. 1) 允许在 js 代码之前加载 HTML。

<script type ="text/javascript">
    window.onload = function what(){
        document.getElementById('hello').innerHTML = 'hi';
    }
</script>

//or set time out like this:
<script type ="text/javascript">
    setTimeout(function(){
       what();
       function what(){
          document.getElementById('hello').innerHTML = 'hi';
       };
    }, 50);
    //NOTE: 50 is milisecond.
</script>

2) Move js code under HTML code 2) 将 js 代码移到 HTML 代码下

<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>

 <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Untitled Document</title> </head> <body> <div id="hello"></div> <script type ="text/javascript"> what(); function what(){ document.getElementById('hello').innerHTML = 'hi'; }; </script> </body> </html>

I have had the same problem and it turns out that the null error was because I had not saved the html I was working with.我遇到了同样的问题,结果是空错误是因为我没有保存我正在使用的 html。

If the element referred to has not been saved once the page is loaded is 'null', because the document does not contain it at the time of load.如果页面加载后引用的元素尚未保存,则为“null”,因为加载时文档不包含它。 Using window.onload also helps debugging.使用 window.onload 也有助于调试。

I hope this was useful to you.我希望这对你有用。

This error can appear even if you load your script after the html render is finished.即使您在 html 渲染完成后加载脚本,也会出现此错误。 In this given example your code在这个给定的例子中你的代码

<div id="hello"></div>

has no value inside the div.在 div 中没有值。 So the error is raised, because there is no value to change inside.所以报错了,因为里面没有值可以改。 It should have been应该是

<div id="hello">Some random text to change</div>

then.然后。

You need to change div into p .您需要将div更改为p Technically innerHTML means it is inside the <??? id=""></???>从技术上讲,innerHTML 意味着它在<??? id=""></???> <??? id=""></???> part. <??? id=""></???>部分。

Change:改变:

<div id="hello"></div>

into进入

<p id="hello"></p>

Doing:正在做:

document.getElementById('hello').innerHTML = 'hi';

will turn会转

<div id="hello"></div> into this <div id="hello">hi</div>

which actually does not make sense.这实际上没有意义。

You can also try to change:您也可以尝试更改:

document.getElementById('hello').innerHTML = 'hi';

into this进入这个

document.getElementById('hello').innerHTML='<p> hi </p> ';

to make it work.使其工作。

Add jquery into < head>将 jquery 添加到< head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

Use $document.ready() : the code can be in < head> or in a separate file like main.js使用 $document.ready() :代码可以在< head>或在一个单独的文件中,比如 main.js

1) using js in same file (add this in the < head> ): 1)在同一个文件中使用js(在< head> ):

<script>
$( document ).ready(function() {
function what(){
    document.getElementById('hello').innerHTML = 'hi';
};
});
</script>

2) using some other file like main.js (add this in the < head> ): 2) 使用其他一些文件,如 main.js(在< head> ):

<script type="text/javascript" src="/path/to/main.js" charset="utf-8"></script>

and add the code in main.js file :)并在 main.js 文件中添加代码:)

该错误是不言自明的,它没有获取您要在其中设置数据的 HTML 标记,因此使标记可用于 JS,然后您只能将数据设置为该标记。

No doubt, most of the answers here are correct, but you can also do this:毫无疑问,这里的大多数答案都是正确的,但您也可以这样做:

document.addEventListener('DOMContentLoaded', function what() {
   document.getElementById('hello').innerHTML = 'hi';  
});

There are different possible cause as discussed would just like to add this for someone who might have the same issue as mine.正如所讨论的,有不同的可能原因只是想为可能与我有相同问题的人添加这个。

In my case I had a missing close div as shown below就我而言,我缺少一个关闭 div,如下所示

   <!DOCTYPE HTML>
   <html>
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Untitled Document</title>
   </head>
   <body>
   <div> //I am an open div
    <div id="hello"></div>
   <script type ="text/javascript">
       what();
       function what(){
          document.getElementById('hello').innerHTML = 'hi';
       };
   </script>
   </body>
   </html>

Missing a close div can result in disorganization of the transversal from child to parent or parent to child hence resulting in an error when you try to access an element in the DOM缺少关闭的 div 可能会导致从子级到父级或父级到子级的横向混乱,因此在您尝试访问 DOM 中的元素时会导致错误

Let the DOM load.让 DOM 加载。 To do something in the DOM you have to Load it first.要在 DOM 中执行某些操作,您必须先加载它。 In your case You have to load the <div> tag first.在您的情况下,您必须先加载<div>标签。 then you have something to modify.那么你有一些东西要修改。 if you load the js first then that function is looking your HTML to do what you asked to do, but when that time your HTML is loading and your function cant find the HTML .如果您首先加载 js,那么该函数正在寻找您的HTML来执行您要求执行的操作,但是当您的HTML正在加载并且您的函数无法找到HTML So you can put the script in the bottom of the page.所以你可以把脚本放在页面的底部。 inside <body> tag then the function can access the <div> Because DOM is already loaded the time you hit the script.<body>标签内,该函数可以访问<div>因为在您点击脚本时已经加载了 DOM。

I have moved my < script > tag below the < body > tag.我已将 < script > 标签移到 < body > 标签下方。 Let's try我们试试看

<body>
    <p>The time is <span id="time"></span>.</p>
</body>

<script>
// Allways keep script at end for date and time object //

    var d = new Date();

    document.getElementById("time").innerHTML = d;
    
</script>

This happened to me when using Django template tags on an if-check to see if there was a value available for a field - if no value I removed everything associated with the value from the page to keep things neat The only problem was the content I removed included the div and id I was trying to work with.当我在 if-check 上使用 Django 模板标签来查看某个字段是否有可用值时,这发生在我身上 - 如果没有值,我从页面中删除了与该值相关的所有内容以保持整洁唯一的问题是我的内容删除包括我尝试使用的 div 和 id。 If there was a value present there was no issue as the div that contained the id I was working with was present.如果存在值,则没有问题,因为包含我正在使用的 id 的 div 存在。 If there was no value I received the error.如果没有价值,我会收到错误。 Once it hit me that's what was going on then easy fix to just add the div in there if the if-check is false.一旦它击中了我,那就是正在发生的事情,然后很容易修复,如果 if-check 为假,只需在其中添加 div。

Before

{% if model.value %}
<div id='my-id'>{{model.value}}</div>
{% endif %}

After

{% if model.value %}
<div>{{model.value}}</div>
{% else %}
<div id='my-id'></div>
{% endif %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM