How To Deal With The “Cannot read property ‘querySelector’ of Null” Error In JavaScript

Are you facing the error “Cannot read property ‘querySelector’ of null” when trying to use the querySelector() to get only the first element? Read to the end of the article. We will show you the cause and how to fix this error.

The cause of this error.

The error “Cannot read property ‘querySelector’ of null” appears when you use the querySelector() method on the DOM element that does not exist. It will be null because of some subjective reasons like:

1. Selecting incorrect DOM element.
2. The element is not defined in the Html file.

Example:

In this example, we use the getElementById() method to get the DOM element in the Html file, but the id ‘register‘ is not defined in Html. Then we use the querySelector() method on this variable so that the error will show when you run this code.

Let’s see the code example below

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<label for="user">User name: </label>
<input type="text" id="user"><br><br>
<button type="submit" text="submit">Submit</button>
</div>
<script src="script.js"></script>
</body>
</html>

script.js

// This is the cause of error; the id 'register' is not defined
const form = document.getElementById('register');
const button = form.querySelector('button');

console.log(button)
button.setAttribute('style', 'color: red;');

Output

The error will show if you try to run this code.

Error: Cannot read property 'querySelector' of Null

To Deal with the “cannot read property ‘querySelector’ of null” error

To solve this error, you must make sure that the value which will be used in the querySelector() method is not null. To do it, use the getElementById() method in the existent id in Html.

Make sure to call the querySelector() on the existing value.

To deal with the error “Cannot read property ‘querySelector’ of null”. First, we call the getElementById() method to select the correct element. Then calling the querySelector() on the existing element. Let’s see the code example below.

// To solve this error, make sure you get the correct id
const button = form.querySelector('button');

console.log(button)
button.setAttribute('style', 'color: red;');

Output

<button type="submit" text="submit"></button>

Website view

Summary

Through this article, you have an idea to fix the “cannot read property ‘querySelector’ of null” in JavaScript by calling the querySelector() on the existing value. We always hope this information will be of some help to you. If you have any questions, Don’t hesitate and leave your comment below.