need_help_ya
need_help_ya

Reputation: 1

I cannot change HTML with .innerHTML. keep getting message "cannot set innerHTML property of null"

My javascript to get the day and time and to place it in the div is as below:

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 looks like this:

<!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>

I keep getting the error message" cannot set property of innerHTML to null". help? Many thanks. i am a beginner.

Upvotes: 0

Views: 217

Answers (4)

Lalit
Lalit

Reputation: 1369

date-and-time is class name and you are accessing it by ID.

Either change attribute name to id or access element by class name or querySelector.

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68383

You need to select element by class instead of id using querySelector

Replace

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

by

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

Upvotes: 1

NineBerry
NineBerry

Reputation: 28499

When looking for an element with an id, that element must exist. You used class instead of id.

False:

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

Right:

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

Upvotes: 2

Muhammet Can TONBUL
Muhammet Can TONBUL

Reputation: 3538

date-and-time is class name not id. You should add id to element,use like this,

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

or change your function, use getElementsByClassName method, Look at this article.

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

Upvotes: 2

Related Questions