我无法使用.innerHTML更改HTML。继续收到消息"不能设置null的innerHTML属性"

时间:2018-01-02 06:18:02

标签: javascript

我的javascript获取日期和时间并将其放入div中,如下所示:

function print(message){
  var div1= document.getElementById("date-and-time");
  div1.innerHTML= message ;
 }
function addZero(i) {
  if (i < 10) {i = "0" + i;}
  return i;
}

function todaysDate (){
  var today= new Date();
  var day= today.getDay();
  var daylist=["Sunday","Monday","Tuesday","Wednesday", 
  "Thursday","Friday","Saturday"];
  var whatDayTime = "<p> Today is " + daylist[day] + ". </p>";
  var hour= addZero(today.getHours());
  var minute= addZero(today.getMinutes());
  var second= addZero(today.getSeconds());
  whatDayTime += "<p> The time is " + hour + ":" + minute+ ":" + second + ".
  </p>";
  return whatDayTime;
} 

print(todaysDate());

HTML看起来像这样:

<!DOCTYPE html>
<html>
<head>
<title>Practice JavaScript</title>
<link rel="stylesheet" href="styles.css">
</head>

<body>
<div class="date-and-time">
</div>

<script src="practice.js"></script>
</body>

我一直收到错误消息&#34;不能将innerHTML的属性设置为null&#34;。救命?非常感谢。我是初学者。

4 个答案:

答案 0 :(得分:2)

date-and-time是类名而不是id。你应该为元素添加id,像这样使用,

<body>
<div class="date-and-time" id="date-and-time">
</div>

或更改您的功能,使用getElementsByClassName方法,Look at this article.

function print(message){
  var div1= document.getElementsByClassName("date-and-time");
  div1[0].innerHTML= message ;
 }

答案 1 :(得分:2)

在查找具有id的元素时,该元素必须存在。你使用的是class而不是id。

题:

<div class="date-and-time"> </div> 

右:

<div id="date-and-time"> </div> 

答案 2 :(得分:1)

您需要使用querySelector

逐个选择元素而不是 id

替换

var div1= document.getElementById("date-and-time");

通过

var div1= document.querySelector(".date-and-time");

答案 3 :(得分:0)

  

日期和时间是类名,您可以通过ID访问它。

将属性名称更改为id或按类名或querySelector更改访问元素。