How to change HTML elements and redirect to another page

I’ve been learning front end web development and thought of challenging myself with an exercise, I have created a simple HTML form

<!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>
</head>
<body>
    <form id="form">
        <label for="name">Name:</label><br>
        <input type="text" id="name"><br>
        <label for="pass">Password:</label><br>
        <input type="password" id="pass"><br><br>
        <input type="submit" value="Submit">
      </form> 

<script src="example.js"></script>
</body>
</html>

and for the JavaScript, this is what I’m using

const form = document.getElementById('form')
const formName = document.getElementById('name')
const formPass = document.getElementById('pass')

const yourName = "John"
const yourPass = "Doe"

form.addEventListener('submit', function(e){
    e.preventDefault()
    if (formName.value == yourName && formPass.value == yourPass) {
    document.querySelector('loginName').innerHTML = yourName;
    window.location.href = 'login.html';
    }
})

What I want here is that after hitting submit, the webpage should redirect to the login .html which only consists of

<!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>
</head>
<body>
    <h1 id="loginName"></h1>
</body>
</html>

After redirecting to login.html I also want it to add the variable yourName from JavaScript to the h1 tag, but this clearly doesn’t work.

Answer

add <script src="example.js"></script> to your login.html file and change example.js to

const formName = document.getElementById('name')
const formPass = document.getElementById('pass')

const yourName = "John"
const yourPass = "Doe"

if(document.URL.indexOf('example.html') != -1){
    form.addEventListener('submit', function(e){
        e.preventDefault()
        if (formName.value == yourName && formPass.value == yourPass) {
            window.location.href = 'login.html';
        }
    })
}

if(document.URL.indexOf('login.html') != -1){
    document.getElementById('loginName').innerHTML = yourName;
}