I’m having problems getting the JS code linked in the innerHTML of my main HTML page working. I have a main HTML file that has these divs:
<div class="content">
<div class="intro">
<img src="nightTree.jpg">
<div class="inner-intro">
<h1>EDUPLANNER</h1>
<p>a student scheduling webapp</p>
</div>
</div>
</div>
<div class="scripts">
<script src="home.js"></script>
</div>
and this is the JS code (home.js) for the main HTML file to insert the innerHTML:
document.addEventListener("DOMContentLoaded", () => {
const content = document.querySelector(".content"),
sidebarLinks = document.querySelectorAll(".sidebar a");
sidebarLinks.forEach(link => {
link.addEventListener("click", event => {
if (link.classList.contains("do-nothing")) {
event.preventDefault();
return;
}
event.preventDefault();
var href = link.getAttribute("href");
fetch("http://127.0.0.1:5500/" + href)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.text();
})
.then(data => {
var parser = new DOMParser();
var parsedDocument = parser.parseFromString(data, "text/html");
if (parsedDocument.querySelector(".day")) {
var script = document.createElement("script");
script.src = "calendar.js";
document.querySelector(".scripts").appendChild(script);
}
content.innerHTML = parsedDocument.body.innerHTML;
})
.catch(error => {
console.error("Error fetching content:", error);
});
});
});
});
This is the CSS for “content” class.
.content {
position: relative;
background-color: rgb(33, 33, 33);
height: 100vh;
width: calc(100% - 80px);
left: 80px;
transition: all 0.5s ease;
padding: 1rem;
}
This is the innerHTML of what I’m trying to get into the main file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<body>
<div class="day"></div>
<script src="calendar.js"></script>
</body>
</html>
and the JS code for the innerHTML:
console.log("Test 1");
document.addEventListener('DOMContentLoaded', () => {
console.log('DOMContentLoaded event fired');
let dayDiv = document.querySelector(".day");
// Simplified for testing
var newDiv = document.createElement("div");
newDiv.textContent = "Test";
dayDiv.appendChild(newDiv);
console.log("For loop executed");
});
console.log("Test 2");
When the innerHTML is loaded on the main page, only “Test 1” and “Test 2” were shown on the console. Everything in document.addEventListener() doesn’t load. I’ve tried changing the fetch codes, where the JS files are parsed and tried window.onload but nothing worked.
P.S. I’m quite new to HTML, CSS and JS so some of my code may be wrong.



