I recently managed to solve my own question: Change colour of selected <li>
But now I have a new issue - since solving the above question, I wanted to change my html files so that they did not all define the same top banner, menu navigation and footer code, it seemed like a waste of space.
So I used Ajax to effectively include html files were I needed them, so now each of my html files have a header and footer element at the top and bottom of the page and the following ajax code fills these header and footer elements with separate html files:
$(document).ready(function () {
fetch("./header.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
fetch("./footer.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});
});
The issue is that now the code that solved my previous issue (linked to at the start of this question) does not work, here is that code:
$(document).ready(function () {
var path = window.location.pathname.substring(1);
path = path.substring(0, path.length - 5);
var pathShort = path.substring(path.indexOf("/")+1);
var activeLink = document.getElementById(pathShort);
activeLink.classList.add("active");
});
I believe the "document.getElementById(pathShort);" call no longer works because technically the element with the id equal to pathShort is not on that page anymore (not in the document), instead it is in the header.html that is included by ajax.
So my question is, how can I search in the included header.html file when calling "document.getElementById(pathShort);"?