0

Hi im getting the error "Uncaught TypeError: Cannot set property 'onclick' of null" ive tried

  • wrapping "window.onload" around my code
  • moving the script link in html at the top and bottom of the page

I haven't found any other solutions online,

Here is my HTML

<!DOCTYPE html>
<html>
    <head>
        <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,700,600' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    </head>
    <body>            
        <div class="Contact">
            Contact
            <a class="a3">
            <i class="fa fa-chevron-up"></i>
            </a>
        </div>
        <script src = "Script.js"></script>
    </body>
</html>

Here is my JS

var arrowThree = document.getElementById("a3");

arrowThree.onclick = function(){
    alert("You clicked on Contact");
};

Of course there is more to my JS and also a css file but its not important to the question

1 Answers1

1

You are using getElementById when there is no element with that id. To do that, you need to add an id to your element:

<a id="a3" class="a3">

or, get by class name:

var arrowThree = document.getElementsByClassName("a3")[0];

However, getting by class name will return an array - be wary of this. In my example, I'm getting the very first element that has the class you're looking for, but this might not always be correct.

If there is more than one element on the page with that class, you can't guarantee you have the right one. This method is more suited if you want to add onClick to all of those elements, like this:

var arrowThrees = document.getElementByClassName("a3");
var clickHandler = function(){
    alert("You clicked on Contact");
}

for (var i=0; i<arrowThrees.length; i++) {
    arrowThrees[i].onclick = clickHandler;
}

Which method you choose depends on whether you want all of those elements to have the onClick, or just one.

millerbr
  • 2,951
  • 1
  • 14
  • 25