Reputation: 1271
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.
Upvotes: 0
Views: 739
Reputation: 1
When the page load starts it will execute the code that is in JS. Trying to execute document.querySelector('button') ...
at this moment will fail because the document (DOM) has not yet been done (parsing), so it does not have the button element yet.
This has two solutions:
Use the defer in the <script>
tag. That will tell the browser to execute the JS after the () of the whole page.
<script src="script.js" defer></script>
Grab the <script src="script.js"></script>
and put in before the end of the </body>
tage. With this, the JS will only run after the page is complete.
Upvotes: 0
Reputation: 68413
I want to understand why this happens and how to write the same thing in vanilla js without getting any errors.
Because when the element with button
class doesn't exists, then $('.button')
doesn't return null, while document.querySelector(".button")
does.
You need to check for null first with vanila js apis
var button = document.querySelector(".button");
button && ( button.onclick = function(){
document.querySelector(".trig").style.display = "block";
});
Upvotes: 3
Reputation: 260
because you write it in wrong way.
you should use it like
$('.button').on("click", function(){
document.querySelector(".trig").style.display = "block";
});
Upvotes: -1