简体   繁体   中英

HTML include using ajax - how to access the included files elements?

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);"?

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.

It's because it isn't in the page when you call getElementById .

It will be after you assign it with innerHTML

So move the code to a point after you assign it with innerHTML .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM