Typescript indicates that an object may be potentially null

I've hit a roadblock where I keep getting warnings that the objects might be null. After searching online and on StackOverflow, I've tried numerous solutions with no luck. My goal is to insert the text "test" into the HTML elements using their IDs.

 var cname = document.getElementById("chargername");
var cloc = document.getElementById("chargerlocation");
var ctype = document.getElementById("chargertype");
var cdesc = document.getElementById("chargerdescription");
var crating = document.getElementById("chargerrating");

function handleClick() {
  cname.innerHTML = "test";
  cloc.innerHTML = "test";
  ctype.innerHTML = "test";
  cdesc.innerHTML = "test";
  crating.innerHTML = "test";
}

I'm facing this error: "TypeError: Cannot set properties of null (setting 'innerHTML')"

Any assistance would be greatly appreciated! Thanks! 😃

Answer â„–1

One reason for this issue could be that the code is being executed before the dom is fully loaded, resulting in a null value.

To troubleshoot, it is important to verify where the script is being loaded.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8&gt;
    <meta http-equiv="X-UA-Compatible" content="IE=edge&gt;
    <meta name="viewport" content="width=device-width, initial-scale=1.0&gt;
    <script src="index.js"></script>  <!-- Placing the script here may cause it to run before the dom is loaded -->
    <title>Document</title>
</head>
<body>
</body>
</html>

If the script is within the head tag, it might execute before the dom is ready.

To ensure the dom is fully loaded before executing scripts, you can use the onLoad function.

You can find an example of how to implement this here.

A solution like the one below should help:

window.onload = function () {
  function getElementById(idName: string): HTMLElement {
    return document.getElementById(idName) as HTMLElement;
  }

  const location = getElementById('chargerlocation');
  const type = getElementById('chargertype');
  const description = getElementById('chargerdescription');
  const rating = getElementById('chargerrating');

  function handleClick() {
    location.innerHTML = 'test';
    type.innerHTML = 'test';
    description.innerHTML = 'test';
    rating.innerHTML = 'test';
  }
};

Answer â„–2

To ensure that TypeScript recognizes the element as non-null, you can use as HTMLElement:

let chargerLocation = document.getElementById("chargerlocation") as HTMLElement;
let chargerType = document.getElementById("chargertype") as HTMLElement;
let chargerDescription = document.getElementById("chargerdescription") as HTMLElement;
let chargerRating = document.getElementById("chargerrating") as HTMLElement;

function handleClick() {
  chargerLocation.innerHTML = "test";
  chargerType.innerHTML = "test";
  chargerDescription.innerHTML = "test";
  chargerRating.innerHTML = "test";
}

Alternatively, you can utilize the exclamation mark !, which serves as the non-null assertion operator. It eliminates null and undefined from the type like so:

let chargerLocation = document.getElementById("chargerlocation");
let chargerType = document.getElementById("chargertype");
let chargerDescription = document.getElementById("chargerdescription");
let chargerRating = document.getElementById("chargerrating");

function handleClick() {
    chargerLocation!.innerHTML = "test";
    chargerType!.innerHTML = "test";
    chargerDescription!.innerHTML = "test";
    chargerRating!.innerHTML = "test";
}

Playground

Answer â„–3

After much trial and error, I finally found a solution to resolve the issue:

let chargerName = docSelect.name;
let chargerLocation = docSelect.location;
let chargerType = docSelect.types;
let chargerDescription = docSelect.description.substring(0, 90) + "...";
let chargerLink = `/chargers/${props}`;
document.getElementsByClassName("chargername")[0].innerHTML = chargerName;
document.getElementsByClassName("chargerlocation")[0].innerHTML = chargerLocation;
document.getElementsByClassName("chargertype")[0].innerHTML = chargerType;
document.getElementsByClassName("chargerdescription")[0].innerHTML = chargerDescription;

A big thank you to all who contributed their assistance to help me overcome this hurdle :)

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

Is it possible to combine ng-switch and ng-if directives in Angular?

I attempted to combine the angular ng-switch and ng-if directives, but it doesn't seem to be functioning properly. Here is what I tried: <div data-ng-if = "x === 'someValue'" data-ng-switch on = "booleanValue"> <div data-ng-swit ...

Issue with defaultValue Prop in Radix UI Accordion when used with Dynamic Child Components

Issue Description: Encountering a problem while utilizing Radix UI's Accordion in a Next.js project. The defaultValue prop seems to be ineffective when the Accordion's children are generated dynamically. Despite setting the defaultValue, the acco ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

"Exploring JSON data with jQuery: A guide to efficient search techniques

I have a local file containing JSON data which I successfully loaded using jQuery. My current task is to specifically find the pId with the value of "foo1". The JSON data { "1":{ "id": "one", "pId": "foo1", "cId": "bar1" }, "2":{ ...

Tips for streamlining a conditional statement with three parameters

Looking to streamline this function with binary inputs: export const handleStepCompletion = (userSave: number, concur: number, signature: number) => { if (userSave === 0 && concur === 0 && signature === 0) { return {complet ...

Encountered an issue while trying to install npm package express-generator globally

Encountering an error when trying to run npm install express? Looking for the correct solution? Read on. -bash-3.2$ npm install express-generator -g npm WARN engine <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a2bfb7b5a2 ...

Selecting multiple objects in FabricJS on mouse click

Can anyone provide suggestions on how to select multiple objects on a canvas with a mouse click? I only want to select objects that overlay the point. From my understanding, the target of the mouse event is always the top-most object. I have tried binding ...

Take a custom action once all elements have been rendered with ng-repeat

Looking to manipulate a DIV element generated by ng-repeat: <div ng-repeat="data in info" > <div id='plot_{{data.id}}'></div> </div> Here is the sequence of events: Information added to $scope.info ng-repeat exec ...

The data stored in the variable cannot be accessed when calling it in a different method

Within my component, there are several methods including constructor(){...} and ngOnInit(){...}. I have declared a variable named values:any=[] in the class, and it is initialized with JSON data within a method called getData(). getData(){ this.service. ...

The combination of Three.js and React

Hello everyone! I am completely new to Three.js and I'm currently attempting to integrate it with React. While looking for resources, I came across this helpful medium article on the topic: Starting with React 16 and Three.js in 5 minutes My goal is ...

Having conflicting useEffects?

I often encounter this problem. When I chain useEffects to trigger after state changes, some of the useEffects in the chain have overlapping dependencies that cause them both to be triggered simultaneously instead of sequentially following a state change. ...

combine object with an array attribute

If we have the following objects: let firstObject = {items: ["apple"]}; let secondObject = {items: ["orange"]}; and then execute Object.assign(firstObject, secondObject); the new state will be: firstObject.items[0] //"orange" firstObject.items === sec ...

Guide to using vite-plugin-rewrite-all in conjunction with Quasar for Vue 3 - or alternative method to enable periods in paths

Encountering a 404 error when using quasar+vite in vueRouterMode: 'history' mode with paths containing a period/dot in the id? This issue has been discussed in various places: https://github.com/vitejs/vite/issues/2415 https://github.com/vitejs/ ...

External JavaScript files cannot be used with Angular 2

I am attempting to integrate the twitter-bootstrap-wizard JavaScript library into my Angular 2 project, but I keep encountering the following error: WEBPACK_MODULE_1_jquery(...).bootstrapWizard is not a function I have created a new Angular app using a ...

Error encountered while executing a join query in Node.js

My stack includes express.js, sequelize, and mysql Database Structure A : { id: 1, name: ... } B : { A_id: 1, name: name1 }, { A_id: 1, name: name2 } A Model (models/A.js) A.association = models => { A.hasMany(models.B, { foreignKey: 'A_id&ap ...

Create a VueJS/VuetifyJS implementation inspired by the WhatsApp swipe between tabs animation

Currently, I am utilizing the VuetifyJS framework for VueJS and I am interested in replicating the swipe between tabs transition seen in WhatsApp for Android. In WhatsApp, you have the ability to swipe left or right to view a new section as you swipe. Vue ...

Incorporating tab navigation and drawer navigation in a React Native Expo application

I am encountering a warning in my react native expo app that uses react navigation 6. Even though I am able to display the tabs and the drawer, I keep getting this console alert: Found screens with the same name nested inside one another. Check Home, Home ...

What is the best way to manage a multi-select dropdown with checkboxes in Selenium Webdriver?

Below is a snapshot of the drop-down I am working with. In order to handle multiple selections, I currently have code that clicks on the arrow in the drop-down and then selects the corresponding checkbox. However, I would like a more efficient solution fo ...

ExpressJS - The execution of JavaScript in this framework does not strictly follow a top-down approach

Having issues with this particular script not running as expected, particularly in the variable reassignment section. Below is the code snippet and output: // Code to Create New Open Market in the game let latestRowId = 1; var sqlQu ...

What is the best way to retrieve the value of the selected mat-option?

I've been struggling to extract the selected value of a mat-option using this specific HTML and TypeScript code. html <mat-form-field appearance="outline" floatLabel="always"> <mat-label>TRA Type</mat-label> ...