You can use local storage if you want an updated DOM after a page reload.
Here’s an example:
<!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>
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"; }
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.