Parvinder Mainn
Parvinder Mainn

Reputation: 61

Uncaught TypeError: Cannot read property 'addEventListener' of null. var one printing null

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

Answers (2)

Lajos Arpad
Lajos Arpad

Reputation: 76434

The error

is telling you that the tag does not exist (yet).

The reason

is that HTML evaluates from top-to-bottom, so your script is evaluated before your tag with that specific id is created.

A simple solution

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.

An elegant solution

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

Daniel Wutz
Daniel Wutz

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

Related Questions