最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot set property 'innerHTML' of null why am I getting this error - Stack Overflow

programmeradmin0浏览0评论
<!DOCTYPE html>

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <div class="demo">heoo</div>
  <script>
    var person = {
      name: "john",
      age: 50
    };
    var result = person.name;
    document.getElementById('demo').innerHTML = result;
  </script>
</body>
</html>

I want to display the person object property value into the div but it is showing can't set innerHTML to null. Please give me some answers.

<!DOCTYPE html>

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <div class="demo">heoo</div>
  <script>
    var person = {
      name: "john",
      age: 50
    };
    var result = person.name;
    document.getElementById('demo').innerHTML = result;
  </script>
</body>
</html>

I want to display the person object property value into the div but it is showing can't set innerHTML to null. Please give me some answers.

Share Improve this question edited Jun 17, 2019 at 21:40 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 20, 2017 at 13:57 janaravijanaravi 1061 silver badge8 bronze badges 1
  • 2 A class is not an id – Andreas Commented Aug 20, 2017 at 13:58
Add a ment  | 

3 Answers 3

Reset to default 3

Change class="demo" to id="demo"

Or your code to:

document.getElementsByClassName('demo')[0].innerHTML= result;

Change your class to id because you are using getElementById so

Getdocumentbyid will search based on ID

If you want to use by class then use like below

var y = document.getElementsByClassName('demo'); y[0].innerHTML= result;

document.getElementById('demo') is trying to get an element from your Html document with an id="demo". It'll not find any element in your Html because it doesn't have any element with id="demo".

You can solve your problem by changing your div class to id (.i.e <div id="demo"> instead of <div class="demo">), or by changing the way you're getting that element from javascript: document.getElementByClassName('demo')[0] instead of document.getElementById('demo')

发布评论

评论列表(0)

  1. 暂无评论