How To Solve “Cannot read property ‘querySelector’ of Undefined” Error in JavaScript

Cannot read property 'querySelector' of Undefined in JavaScript

Are you finding a way to solve the error “cannot read property ‘querySelector’ of undefined” in JavaScript? Let’s follow this article. We will help you to fix it.

The cause of this error.

The main reason for the cannot read property ‘querySelector’ of undefined error is a logic error in your code because you are not creating the value for the DOM element first and trying to call out the querySelector() method on this element.                                     

Before calling the querySelector(), you can make sure that the variable is valid.


In the Index.html file:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <h1 id="header"></h1>
    <div id="message">
      <h2 id="greeting">LearnShareIT : Merry Christmas and Happy New Year</h2>
    <script src="script.js"></script>

In the script.js file:

// Set the undefined
const element = undefined;

// This is the cause of this error 
const receivedElement = element.querySelector('#greeting');

// Check for null before changing
if (receivedElement != null) {
	receivedElement.setAttribute('style', 'color: red;');

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


TypeError: Cannot read properties of undefined (reading 'querySelector')

To Deal with “Cannot read property ‘querySelector’ of Undefined” Error

We’ve tested effectively by using the getElementbyId solutions to solve the error. Reading to the end of the article to see how we solve this problem.

Using the getElementById() method.

To avoid this error, you can use a getElementById() method to make sure the variable is valid and always defined. This function will return an element with a specified value and is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.


// Using the getElementById to get out the specified value to use querySelector method
const element = document.getElementById("message");

// Using querySelector() method on element
const receivedElement = element.querySelector("#greeting");

// Check for null before changing
if (receivedElement != null) {
    receivedElement.setAttribute("style", "color: red;");



<h2 id="greeting" style="color: red;">LearnShareIT : Merry Christmas and Happy New Year</h2>

Website view:

LearnShareIT: Merry Christmas and Happy New Year


In this article, we already explained to you how to solve the errorCannot read property ‘querySelector’ of Undefined” in JavaScript by Using the getElementById() method. We always hope it’s helpful to you. If you have any questions, Don’t hesitate and leave your comment below.

Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *