The null object does not have a property addEvenListener and therefore cannot be

My goal is to develop a simple single-page application without using any frameworks, focusing on providing users with tutorials on specific subjects.

I am encountering an issue with the javascript code for my page, receiving the following error:

Uncaught TypeError: Cannot read property 'addEventListener' of null

Below is the snippet of javascript I am utilizing to fetch and load JSON data:

var btn = document.getElementById("btn");

btn.addEventListener("click", function(){
  var TutRequest = new XMLHttpRequest();
  TutRequest.open('GET', 'https://api.myjson.com/bins/iyvun');
  TutRequest.onload = function(){
    var TutData = JSON.parse(TutRequest.responseText);
    console.log(TutData[2]);
   };
 TutRequest.send();
})

This is the HTML code used in my project:

<html>
<head>
    <meta name="viewport" content="width=devide-width, initial-scale=1"/>
    <title>SPA Tutorial page</title>
    <link rel="stylesheet" href="css/styles.css">
    <script src="javaScript.js"></script>
</head>

<body>

    <header>
    <h1>SPA tutorials</h1>

        <nav role="navigation">
            <ul>
                <li><a href="#the-default-view"><button id="btn">the default view</button></a></li>
                <li><a href="#some-view"><button id="btn2">some view</button></a></li>
                <li><a href="#another-view"><button id="btn3">another view</button></a></li>
            </ul>


        </nav>
    </header>

</body> 

Despite the expected outcome being the display of JSON data from the specified URL in the JS code, I'm consistently facing this particular error no matter what I attempt. Any assistance or guidance regarding this issue would be greatly appreciated.

Answer №1

The reason this occurs is because the DOM is not fully loaded when the script runs. To solve this issue, place your JS include at the end of the body tag. This way, the elements that you want to attach events to will be ready and loaded. Here is an example:

<html>
<head>
    <meta name="viewport" content="width=devide-width, initial-scale=1"/>
    <title>SPA Tutorial page</title>
    <link rel="stylesheet" href="css/styles.css">
</head>

<body>

    <header>
    <h1>SPA tutorials</h1>

        <nav role="navigation">
            <ul>
                <li><a href="#the-default-view"><button id="btn">the default view</button></a></li>
                <li><a href="#some-view"><button id="btn2">some view</button></a></li>
                <li><a href="#another-view"><button id="btn3">another view</button></a></li>
            </ul>


        </nav>
    </header>

    <script src="javaScript.js"></script>
</body> 
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for executing a nested query in the Parse API?

Within the user object, there is a list of features: skills: {"piano:10", "singing:5", ....}; I am looking to filter users based on their 'piano' skills. How can I achieve this? It doesn't have to be an exact match but should follow the ru ...

`CSS animation for vanishing line effect`

I want to create an animated logo that gives the illusion of being pulled up by a rope, represented by a vertical black line, from the bottom of the page to the top. As the logo moves upwards, I would like the rope to disappear behind it, but I'm uns ...

Issue: Alert: Middleware for RTK-Query API designated as reducerPath "api" is missing from store configuration even though it has been included

Currently in the process of migrating my application to NextJS, and I'm dealing with the following store configuration. It's a bit messy at the moment, but I plan on cleaning it up and reducing duplicated code once I have everything functioning p ...

Encountering difficulties during the migration process from a JavaScript to a TypeScript React Component

I've encountered some challenges with configuring TypeScript in my project. Initially, I developed my application using plain JavaScript. However, eager to learn TypeScript, I decided to convert my JavaScript project into a TypeScript one. To achiev ...

The powerful ASP file upload feature

Currently, I am utilizing a dynamic ajax file upload control called AjaxControlToolkit.AsyncFileUpload(). However, when attempting to upload a file, the value of Request.ServerVariables["QUERY_STRING"] is displaying as "AsyncFileUploadID=MainContent_flbFi ...

What is the correct way to establish and terminate a MongoDB connection in a Node.js application?

Hey everyone, I have a piece of code at this link (https://github.com/MrRav3n/Angular-Marketplace/blob/master/server.js) and I'm curious if I am properly starting and ending my database connection. Should I connect and end the db connection in every a ...

Tips on comparing a string against an object's value

I need to compare the key values of an object with the strings yes or no. I am encountering difficulties in achieving this comparison and updating radio buttons accordingly based on the comparison. Here is the code snippet: const screenJson = { Managem ...

AngularJS: Refresh array following the addition of a new item

After saving an object, I am looking to update an array by replacing the conventional push method with a custom function. However, my attempts have not been successful so far. Are there any suggestions on how to rectify this issue? app.controller("produ ...

How to extract dynamic content efficiently by combining Selenium and Scrapy for multiple initial URLs

I have been assigned the task of developing a web scraper for a property website where the data will be collected and stored for future analysis. The website is a national platform that requires users to select a region before displaying any results. In ...

Consistently encountering the error message "(0 , _reactDom.h) is not a function" or "h is not defined"

I'm currently in the process of developing an app that makes use of electron, react, redux, and several other technologies. At the moment, I have included electron, react, electron-compile, and babel in the project. Redux is installed but has not been ...

Navigating an array of JSON objects with the http client and Observables in Angular: A Step-by-Step Guide

Here is the URL I want to make an HTTP request from a service in Angular: The data consists of an Object containing an array of Features. The Features array includes 4 Objects - type, properties, geometry, and id. I aim to store the properties and geomet ...

Using a variable as a parameter when requesting a value from a JSON object in JavaScript

I consider myself to be at an intermediate level in JavaScript, but I've hit a roadblock when trying to access the key in a JSON message that is returned to me. My code is dynamic, so I need to pass the key into the query. For example: After running ...

Tips for implementing personalized command buttons in Kendo Grid with AJAX request utilizing JavaScript

I am struggling with implementing custom command buttons in a Kendo grid that makes an AJAX call using JavaScript to call a web API post action with dynamic parameters (start, stop, restart) behind button clicks. datasource dataSource = new ken ...

Mapping YAML file to a Java Map without using a custom deserializer

I have a YAML file that I want to load into a Map instance without having to define a custom deserializer. Is there a way to achieve this using annotations or any other method? Below is an example of the YAML file: - site: First Site url: some_url us ...

Is it possible to customize the font color of a placeholder in a v-text-field component in Vue?

Recently, I added the following code snippet to my project: <v-text-field hide-details class="search-field" id="name-input" placeholder="Search by name" v-model="search"></v-text-field> I wanted to change the font color of the placeholder tex ...

Mastering the art of navigating through multiple nested objects is achievable by harnessing the power of recursive

I'm utilizing the AngularTree directive in my Angular application to display a tree view of a specific data structure. The data structure can be viewed at https://jsfiddle.net/eugene_goldberg/Lvwxx629/17/. You can find more information about the Angul ...

Is there a way to show a Django template message after selecting a value from a dropdown list that meets a condition in the main table?

I am working on a form that consists of fields that are foreign keys to their respective parent models. Here is an example: class vehicle(models.Model): STATUS = [ (OPERATIONAL, ('Operational')), (GROUNDED, ('Grounded&apo ...

Maintain checkbox selection even after the page is refreshed

Having trouble fetching all objects from the favorites array and setting the checkbox to checked. I've attempted using localStorage but the values are not saved after refreshing, despite researching online for solutions. Any assistance would be great ...

What makes this plugin capable of uploading files through ajax?

Why is this ajax upload file plugin using plain ajax when we know that files cannot be uploaded via ajax? _upload: function(id, params){ var file = this._files[id], name = this.getName(id), size = this.getSize(id); ...

Setting the cache to false during an httpget request in an mvc4 controller action: tips and tricks

My httpget request to a controller action looks like this: $.get('/Course/ExplanationCorrect/', postData, function (data) { $('#SurveyDiv').html(data); }); While it works on all other browsers, I'm facing an issue with IE10 o ...