You can use local storage if you want an updated DOM after a page reload.

Here’s an example:

1 Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./script.js"></script>
</head>
<body>
    <nav>
        <button onclick="changeRoute('home')">Home</button>
        <button onclick="changeRoute('about')">About</button>
        <button onclick="changeRoute('contact')">Contact</button>
    </nav>
    <section>
        <div id="home" class="page">
            <h1>Home page</h1>
        </div>
        <div id="about" class="page">
            <h1>About page</h1>
        </div>
        <div id="contact" class="page">
            <h1>Contact page</h1>
        </div>
    </section>
</body>
</html>

2 Script.js

window.onload = function() {
    const pages = document.getElementsByClassName("page");
    for(const page of pages) {
        page.style.display = "none";
    }
    document.getElementById('home').style.display = "block";
}

const changeRoute = (route) => {
    const pages = document.getElementsByClassName("page");
    for(const page of pages) {
        page.style.display = "none";
    }
    const selectedPage = document.getElementById(route);
    selectedPage.style.display = "block";
}
  • In the above example, I am toggling divs based on the selected route instead of making separate HTML files.
  • So when I click on the contact button, the ‘Contact Page’ header will appear, but whenever I refresh the page, it will revert back to the home page section.
  • Below is an updated script.js to keep changes to the DOM.

script.js

window.onload = function() {
    const pages = document.getElementsByClassName("page");
    for(const page of pages) {
        page.style.display = "none";
    }
    const selectedPage = localStorage.getItem('selectedPage');
    if(selectedPage) {
        document.getElementById(selectedPage).style.display = "block";
    }
    else {
        document.getElementById('home').style.display = "block";
    }
}

const changeRoute = (route) => {
    const pages = document.getElementsByClassName("page");
    for(const page of pages) {
        page.style.display = "none";
    }
    const selectedPage = document.getElementById(route);
    localStorage.setItem('selectedPage', route);
    selectedPage.style.display = "block";
}

Here, the browser knows the previous changes to the DOM. So, when we refresh the page, it will give us an updated result.

Note: Here you can also use session storage instead of local storage.

Support On Demand!

                                         
JavaScript