Reputation: 61
console.log("connected");
var one = document.getElementById("Click")
console.log(one);
one.addEventListener('click',function a() {
one.textContent = 'Clicked';
})
Even Variable one is printed null in console
The HTML code is:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="x.js"></script>
<h1 id="Click">Click</h1>
</body>
</html>
Upvotes: 2
Views: 2351
Reputation: 76434
is telling you that the tag does not exist (yet).
is that HTML evaluates from top-to-bottom, so your script is evaluated before your tag with that specific id is created.
is the following:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1 id="Click">Click</h1>
<script src="x.js"></script>
</body>
</html>
This evaluates your tag first and then the script which assumes its existence. Even though this should work, it's assuming some rules in your HTML, which is not very elegant.
is the following:
function load() {
console.log("connected");
var one = document.getElementById("Click")
console.log(one);
one.addEventListener('click',function a() {
one.textContent = 'Clicked';
})
}
and
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="x.js"></script>
</head>
<body onload="load()">
<h1 id="Click">Click</h1>
</body>
</html>
because this does not hinder your autonomy in writing and maintaining your HTML. The idea is that a function is created, which is triggered when body
is loaded. When body
is loaded, you can be sure that your h1
is also loaded.
Upvotes: 0
Reputation: 76
Keith's answer works. But a cleaner way is to only add the event listener if the DOM has loaded (i.e., assign your code to the window.onload
function). That way, you can leave the <script>
-Tag whereever you want (recommended is within <head></head>
).
And remove the a from function a()
, because you are passing the function in as an anonymous function and thus it should have no name. Like this:
window.onload = function() {
console.log("connected");
var one = document.getElementById("Click");
console.log(one);
one.addEventListener('click', function() {
one.textContent = 'Clicked';
});
};
Upvotes: 1