For some reason, my browser cannot read the variable I declared with contents of the HTML DOM. My code doesn't work when I use Microsoft's Live Preview extension to open my work in a browser window. However, if I open the html file in a browser window(show preivew(external browser)) and then import the content of my js file into the console instead of having the js file immediately linked, it works.
For the latter situation, I only get this error: 'Uncaught TypeError: Cannot read properties of null'
My html code
<!DOCTYPE html>
<html lang="en">
<head>
<script src="challenge1Copy.js"></script>
<title>Changing Doc Text</title>
</head>
<body>
<header>
</header>
<p>Some example code</p>
<!--button meant to call event handler-->
<button>Click here!</button>
<footer>
</footer>
</body>
</html>
My js code
//Displays the current time and date
const day = new Date();
//Displays the current hours
let hours = day.getHours();
//Displays the current minutes
const minutes = day.getMinutes();
//Displays the current seconds
const seconds = day.getSeconds();
//Displays the current day as a number value
let currentDay = day.getDay();
//Changes the number value of the day into a word format
switch (currentDay) {
case 0:
currentDay = 'Sunday';
break;
case 1:
currentDay = 'Monday';
break;
case 2:
currentDay = 'Tuesday';
break;
case 3:
currentDay = 'Wednesday';
break;
case 4:
currentDay = 'Thursday';
break;
case 5:
currentDay = 'Friday';
break;
case 6:
currentDay = 'Saturday';
break;
Default:
console.log('currentDay variable is not working')
break;
}
//Declaring and defining a time suffix variable to be able to display am and pm
let timeSuffix = '';
//Setting terms for when to use am and when to use pm
if (hours >= 12) {
timeSuffix = 'PM';
} else {
timeSuffix = 'AM';
}
//Converting 24 hour time to 12 hour time format
if (hours > 12) {
hours = hours - 12;
}
//finds button in html doc
let realButton = document.querySelector('button');
//event to change paragraph content to current date and time
realButton.addEventListener('click', function (e){
let dayAndTime = document.querySelector('p')
dayAndTime.innerText = `Today is : ${currentDay}.\nCurrent time is : ${hours} ${timeSuffix} : ${minutes} : ${seconds}`;
})
I just want to figure out why my js code works only when manually injected into the console when the html file is open in a browser. This seems to be the only case in which my code works at all.