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.
2
Answers
It seems like the issue might be related to the way you’re handling the dynamic loading of content and scripts. When you fetch the content and insert it into the main HTML document, the scripts in the fetched content may not be executing as expected.
Here are a few suggestions to troubleshoot and improve your code:
Execute the Script Manually:
Instead of directly appending the script element to the document, you can create a new script element, set its content to the script code, and then append it to the document head. This can be done using the
innerHTML
property.Use the
insertAdjacentHTML
Method:Instead of setting
content.innerHTML
, you can use theinsertAdjacentHTML
method to insert the content at a specified position. This may help in ensuring that the script is executed.Separate Loading and Execution:
Ensure that the script is loaded and executed separately. You can load the script using the
fetch
API and then execute it using theFunction
constructor.You can’t add JS like you add HTML elements.
To add JS you need to do it like this…
Btw, you should replace all instances of…
with…
DOMContentLoaded is too premature to be suitable for your needs, unless taking loading measurements which you’re not.