I have two pages, page1.html & page2.html, they link to the same javascript file.
This is the markup for page 1
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button class="button">HIT ME</button>
<div class="trig"></div>
</body>
<script src="jquery.min.js"></script>
<script src="script.js"></script>
</html>
and page 2
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button class="button_2">HIT ME</button>
</body>
<script src="jquery.min.js"></script>
<script src="script.js"></script>
</html>
and this is the script
document.querySelector(".button").onclick = function(){
document.querySelector(".trig").style.display = "block";
}
When I refresh page 2 I get
Uncaught TypeError: Cannot set property 'onclick' of null error
obviously because it can't find the .button class
But when I write the same thing in jquery it runs gracefully with no errors in both pages.
$('.button').click(function(){
$('.trig').show();
});
I want to understand why this happens and how to write the same thing in vanilla js without getting any errors.
.buttonon your second page