tutorial

[SOLVED] “auth/unauthorized domain” error in Firebase Auth

In this article, we’re going to learn how to easily fix the “auth/unauthorized domain” error which happens in the Firebase Authentication Web SDK.

What causes “auth/unauthorized domain” error in Firebase?

The Firebase “domain is not authorized” error happens when you try to use an API from Firebase Auth in a domain that is not authorized by Firebase.

It may occur in the FirebaseUI, or in your browser console.

The “auth/unauthorized” Firebase error occurring in FirebaseUI.

How to fix “auth/unauthorized domain” error in Firebase

To fix the “Domain not authorized” error in Firebase Auth, go to the Firebase Authentication Authorized domains settings for your project, using this link: https://console.firebase.google.com/project/_/authentication/settings.

Or by following these steps from the Firebase Console for your project in this image:

An image with steps to go to the Firebase Authentication Authorized domains settings page.

Enter the new domain in the dialog that shows after clicking Add domain:

Enter the new domain to register it as an authorized domain in Firebase Authentication.

How to get URL query string parameters in Next.js

Query parameters are used to pass data from the URL to the web server or browser. They are essential for customizing user experiences, filtering data, and tracking user actions.

Displaying the URL query parameters in a Next.js app.

Let’s learn how to easily get the query string parameters from a URL in a Next.js app.

In this article

Get URL query params in Next.js App Router client component

To get the URL query string parameters in the Next.js app directory, use the useSearchParams() hook from next/navigation.

app/amazing-url/page.tsx
'use client'; import { useSearchParams } from 'next/navigation'; export default function Home() { const searchParams = useSearchParams(); const query = searchParams.get('q'); return ( <> Welcome to Coding Beauty <br /> <br /> Your query: <b>{query}</b> </> ); }

We need ‘use client’ to use useSearchParams()

Notice the 'use client' statement at the top.

It’s there because all components in the new app directory are server components by default, so we can’t use any client-side specific functionality like hooks and animations.

We’ll get an error if we try to do anything interactive with useSearchParams or other hooks like useEffect, because it’s a server environment.

Get URL query params in Next.js Pages Router component

To get the URL query string parameters in pages directory component, use the query property of the useRouter() hook, which comes from the next/router module:

pages/coding-tips.tsx
import Head from 'next/head'; import { useRouter } from 'next/router'; export default function Home() { const router = useRouter(); const greeting = router.query.greeting; return ( <> <Head> <title>Coding Tips | Coding Beauty</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.icon" /> </Head> <main> <h2>{greeting}</h2> <p>Appreciate the beauty of coding</p> </main> </> ); }

Get URL query params in Next.js middleware

To get the URL query string parameters in Next.js App or Pages Router middleware, use the request.nextUrl.searchParams property:

middleware.ts
import { NextResponse } from 'next/server'; import { NextRequest } from 'next/server'; export function middleware(request: NextRequest) { const continueUrl = request.nextUrl.searchParams.get('continue')!; return NextResponse.redirect(continueUrl); }

Get URL query params in Next.js server component

To get the URL query params in a server component, se the URL as a header in middleware, then parse this URL in the server component to get the query string and parameters:

middleware.ts
import { NextResponse } from 'next/server'; import { NextRequest } from 'next/server'; export function middleware(request: NextRequest) { const reqHeaders = new Headers(request.headers); // toLowerCase() to avoid 404 due to Next.js case-sensitivity const url = request.url.toLowerCase(); reqHeaders.set('x-url', url); return NextResponse.next({ request: { headers: reqHeaders, }, }); }
app/search/page.tsx
import { headers } from 'next/headers'; export default function Page() { const headerList = headers(); const url = headerList.get('x-url')!; const query = new URL(url).searchParams.get('q'); return ( <> <h2>Welcome to Coding Beauty.</h2> <p>Your query: {query}</p> </> ); }

Get URL query params in getServerSideProps()

To get the URL query string params in the Pages Router getServerSideProps() function, use the context.query property:

pages/random-lyrics.tsx
export async function getServerSideProps(context) { const { songId } = context.query; const res = await fetch(`https://api.example.com/lyrics?songId=${songId}`); const lyrics = await res.json(); return { props: { lyrics, }, }; } export default function LyricsPage({ lyrics }) { const { song, content } = lyrics; return ( <div> {song} lyrics<div>{content}</div> </div> ); }

Get URL query params in Next.js Pages Router API

To get the URL query string parameters in an API in the pages directory, use the request.query property:

pages/api/stock-prices.tsx
import type { NextApiRequest, NextApiResponse } from 'next'; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { name } = req.query; const stockRes = await fetch(`api.example.com/stock-prices?name=${name}`); const stockData = await stockRes.json(); res.status(200).json({ stockData }); }

Get URL query params in Next.js App Router API

To get the URL query string params in an API in the Next.js 13 app directory, use the request.nextUrl.searchParams property:

app/api/forecast/route.ts
import { NextRequest, NextResponse } from 'next/server'; const data = { 'new-york': { summary: 'sunny' } // ... } export async function GET(req: NextRequest) { const location = req.nextUrl.searchParams.get('location'); const weatherData = data[location]; return NextResponse.json({ weatherData }); }

[SOLVED] Could not find an option named “no-sound-null-safety” in Flutter

Are you experiencing the “Could not find an option named no-sound-null-safety” error in Flutter?

The "Could not find an option named no-sound-null-safety" occurring in VS Code.
The “Could not find an option named no-sound-null-safety” occurring in VS Code.

We’re going to learn how to easily fix it in this article.

What causes the “Could not find an option named no-sound-null-safety” error?

The “Could not find an option named no-sound-null-safety” happens in a newer Flutter project using Dart 3.0, because Dart no longer supports unsound null safety.

Unsound null safety was a special Dart/Flutter feature where there are no static checks to ensure that we don’t access nullable variables – variables that may be null.

It allowed developers to migrate their codebase to the default null safety gradually without breaking existing code that depended on null-unsafe libraries.

But from version 3.0 upwards, Dart only supports code using sound null safety.

Fix “Could not find an option named no-sound-null-safety” (general)

To fix the “Could not find an option no-sound-null-safety” Flutter error, remove the --no-sound-null-safety option in your flutter run command.

The "Could not find an option named no-sound-null-safety" occurring in the command line.

Fix “Could not find an option named no-sound-null-safety” in VS Code

To fix the error in Visual Studio Code remove the --no-sound-null-safety option in the Dart: Flutter Additional Args setting.

You can use the Ctrl + , keyboard shortcut to quickly open the Settings page.

[Solved] Cannot find module in Node.js (MODULE_NOT_FOUND)

Are you experiencing the “Cannot find module” or MODULE_NOT_FOUND error in your Node.js project?

This error happens when your IDE can’t detect the presence of a particular NPM package. Let’s see how easy it is to fix.

In this article

1. Ensure NPM package installed

To fix the “Cannot find module” error in Node.js, make sure the NPM package is installed and present in your package.json file.

You can install a package from NPM with the npm i command, for example:

Shell
# NPM npm i nextjs-current-url # Yarn yarn add nextjs-current-url # PNPM pnpm add nextjs-current-url

After installation, the package will included under the dependencies field in package.json

package.json
{ ... "dependencies": { ... "nextjs-current-url": "^1.0.1" ... } ... }
Installed NPM packages are in the package.json dependencies key

You can also install the package as a development dependency, which indicates that the package is only used for development, and won’t be needed by the app itself. Packages like nodemon and ts-node fit this category:

Shell
# NPM npm i -D ts-node # Yarn yarn add -D ts-node # PNPM pnpm add -D ts-node

It will be part of devDependencies in package.json after installation:

package.json
{ ... "devDependencies": { ... "ts-node": "^10.9.1" ... } }

2. Install package again

To fix the MODULE_NOT_FOUND error in Node.js, trying installing the package in your project once again, even if you did so earlier:

Shell
# NPM npm i -D try-catch-fn # Yarn yarn add try-catch-fn # NPM yarn add try-catch-fn

3. Reinstall all packages

Try removing the NPM packages installed in your project and reinstalling them again, to fix the “Cannot find module” error.

You can do this with the following command sequence:

Shell
# NPM rm package-lock.json rm node_modules -r npm cache clear npm install # Yarn rm yarn.lock rm node_modules -r yarn cache clean yarn install # PNPM rm pnpm-lock.yaml rm node_modules -r pnpm store prune pnpm install

npm cache clear helps to rid the package manager cache of any corrupted module files.

4. TypeScript: Install type definitions

The MODULE_NOT_FOUND error will occur when you import a package that doesn’t have any detected type definitions into a TypeScript file.

If it’s a core Node.js module like http or fs, you may need to add "node" to compilerOptions.types in your tsconfig.json file:

tsconfig.json
{ // ... "compilerOptions": { // ... "types": [ "node" ] // ... }, // ... }

If it’s a third-party module, installing the type definitions from NPM should help. For example:

JavaScript
npm i @types/express

5. Ensure package.json main file exists

You may encounter the “Cannot find module” error in Node.js if the main field of your package.json file doesn’t exist.

The file in the package.json main field doesn't exists.

You can also try the npm link command on the package to fix the MODULE_NOT_FOUND error, for example:

Shell
npm link create-react-app npm link webpack

npm link is a command that connects a globally installed package with a local project using a symbolic link.

It enables working on a package locally without publishing it to the npm registry or reinstalling it for every change. Executing npm link in the package directory establishes a symbolic link in the global node_modules directory, directing to the local package.

Afterwards, npm link <package-name> can be used in the project to link the global package with your local project.

7. Ensure correct NODE_PATH

In older Node.js versions, you may be able to fix the “Cannot find module” error by setting the NODE_PATH environment variable to correct node_modules installation folder.

NODE_PATH is a string of absolute paths separated by colons used by Node.js to locate modules when they can’t be found elsewhere.

It was initially created to enable the loading of modules from different paths when there was no defined module resolution algorithm.

And it’s still supported, but it’s not as important anymore since the we’ve established a convention for finding dependent modules in Node.js community.

How to easily fix the “Command not found” error in VS Code

Are you developing a Visual Studio Code extension and experiencing the “Command not found” error? Let’s learn how to fix it in this article.

In this article

1. Register command in package.json contributes

To fix the “Command not found” error in a VS Code extension, make sure your extension registers the command under the contributed field in your package.json file:

package.json
{ ... "contributes": { "commands": [ ... ] } ... }

2. Register command in package.json activationEvents

To fix the “Command not found” error in a VS Code extension, make sure you’re added the command to the activationEvents array in your package.json file:

package.json
{ ... "activationEvents": [ "onCommand:extension.showMyExtension", "onCommand:extension.callMyExtension" ] ... }

3. Check console logs for any errors

One common cause of “Command not found” error in a VS Code extension is an undetected JavaScript error. You may find such errors when you examine the VS Code console logs.

Head to the Help menu and select Toggle Developer Tools and inspect the console for potential errors.

4. Register command in extension.ts registerCommand()

To fix the “Command not found” error in a VS Code extension, make sure you’re registered the command in extension.ts using vscode.commands.registerCommand():

JavaScript
// ... export async function activate(context: vscode.ExtensionContext) { // ... // commandAction is a callback function context.subscriptions.push( vscode.commands.registerCommand('command_name', commandAction) ); // ... }

5. Compile TypeScript source manually

The “Command not found” error happens in a VS Code extension if the TypeScript source wasn’t compiled to the out folder before launch or build.

This typically indicates a problem with your VS Code debug configuration, for example, preLaunchTask may be missing from launch.json:

launch.json should have a preLaunchTask which builds the VS Code extension's TypeScript files automatically.
launch.json should have a preLaunchTask which builds the TypeScript files automatically.

Or there may be a problem with the build script in package.json.

package.json
{ ... "scripts": { ... "vscode:prepublish": "npm run esbuild-base -- --minify && npm run build", "esbuild-base": "rimraf out && esbuild ./ext-src/extension.ts --bundle --outfile=out/extension.js --external:vscode --format=cjs --platform=node", "build": "webpack && tsc -p tsconfig.extension.json", ... } ... }

While you figure out what’s preventing the automatic TypeScript compilation, you can do it yourself with the tsc command:

Shell
# NPM npx tsc -p . # Yarn yarn tsc -p . # PNPM pnpm tsc -p .

6. Upgrade VS Code to match extension version

To fix the “Command not found” error in an extension, update VS Code to a version higher that what is specified in the engines.vscode field of your package.json file.

Or, downgrade engines.vscode to a version equal to or lower than the VS Code version you’re using to run the extension.

package.json
{ ... "engines": { "vscode": "^1.80.0" }, ... }

How to easily fix the EAI_AGAIN error in NPM, Yarn, or PNPM

The EAI_AGAIN error happens during an NPM, Yarn, or PNPM installation when the target server or DNS server doesn’t respond within a set time limit. This could happen due to network congestion, DNS server failures, or other connection issues.

Let’s explore some effective methods for quickly fixing the EAI_AGAIN error.

In this article

1. Clear NPM proxy

To fix the EAI_AGAIN error in NPM, Yarn, or PNPM, try removing the proxy settings from your configuration with this command:

Shell
# NPM npm config rm proxy npm config rm https-proxy # Yarn Classic (v1) yarn config delete proxy yarn config delete https-proxy # Yarn Berry (v2+) yarn config unset httpProxy yarn config unset httpsProxy # PNPM pnpm config delete proxy pnpm config delete https-proxy

2. Use faster internet connection

One simple and effective method can be to switch to a faster internet connection. Steer clear of activities that could consume additional data and leave less bandwidth for the package manager. This includes closing all unnecessary browser tabs and other data-consuming applications.

3. Retry command

Quite frequently, the EAI_AGAIN error can be temporary due to brief DNS server issues or network instability. Simply retrying the NPM/Yarn/PNPM command may solve the problem.

4. Clear package manager cache

In NPM and Yarn cache may also be a cause of the EAI_AGAIN error. Try retrying your command after clearing the cache with this command:

Shell
# NPM npm cache clean --force # Yarn yarn cache clean

5. Use different DNS server

Sometimes, the DNS server you’re using may be facing issues. Using a different DNS server like Google’s public DNS (8.8.8.8 and 8.8.4.4) or the one from Cloudflare (1.1.1.1 and 1.0.0.1) might help too.

Changing the DNS server on Windows to fix the EAI_AGAIN NPM error.
Changing the DNS server on Windows. Source: How to configure Cloudflare’s 1.1.1.1 DNS service on Windows 11, 10, or router

6. Reboot computer or server

As with many other technical issues, sometimes a simple reboot of your computer or server can fix minor problems that may contribute to the error.

7. Disable VPN or proxy

Sometimes, using a VPN or proxy at the OS level makes your package manager have connection issues. In this case, try disabling your VPN or proxy and run the NPM/Yarn/PNPM command again.

8. Connect to another network

If you’re still facing the EAI_AGAIN error, switch to a completely different network. This can help bypass potential network-specific issues causing the error.

9. Flush DNS cache

Clearing your computer’s DNS cache can also help resolve DNS-related issues that may be causing the EAI_AGAIN error. On Windows, you can do this with ipconfig /flushdns. 4 Ways to Flush the DNS Cache to Fix Web Browsing Errors.

10. Release and renew IP address

Another plausible solution to the EAI_AGAIN error can be releasing and renewing your IP address. Your IP address is what connects your computer to your network, and sometimes a bad IP configuration could possibly cause network errors.

On Windows, you can do this with ipconfig /release and ipconfig /renew. How to Reset IP Address: Mac, Windows, Linux & More.

11. Use different NPM registry

If the issue persists, try switching to a different NPM registry. For example, you can switch to the official NPM registry by running:

Shell
# NPM npm config set registry https://registry.npmjs.org/ # Yarn Classic (v1) yarn config set registry https://registry.npmjs.org/ # Yarn Berry (v2+) yarn config set npmRegistryServer https://registry.npmjs.org/ # PNPM pnpm config set registry https://registry.npmjs.org/

12. Temporarily disable antivirus or firewall

In some cases, security software like antivirus or firewall programs can interfere with network requests to NPM and cause the EAI_AGAIN error. Temporarily disable them and see if it resolves the issue.

13. Update package manager and Node.js

Make sure you are using the latest versions of Node.js and NPM, Yarn, or PNPM. You can update npm by running:

Shell
# NPM npm i -g npm@latest # Yarn npm i -g yarn@latest # PNPM npm i -g pnpm@latest

14. Try again later

Finally, if none of the above works, it may be a temporary problem with the registry server – the only thing you can do in this case is to wait for a while and then retry. Patience can sometimes be the most effective solution.

How to get the difference between two arrays in JavaScript

Get asymmetric difference between two arrays

To get the difference between two arrays in JavaScript, use the filter() and include() array methods, like this:

JavaScript
function getDifference(arrA, arrB) { return arrA.filter((element) => !arrB.includes(element)); } const arr1 = [1, 2, 3, 4]; const arr2 = [2, 4]; console.log(getDifference(arr1, arr2)); // [1, 3]

Array filter() runs a callback on every element of an array and returns an array of elements that the callback returns true for:

JavaScript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const evenNumbers = numbers.filter( (number) => number % 2 === 0 ); console.log(evenNumbers); // [2, 4, 6, 8, 10]

The Array includes() method returns true if the Array contains a particular element and returns false if it doesn’t:

JavaScript
const arr = ['a', 'b', 'c']; console.log(arr.includes('b')); // true

If we wanted to find the difference between two Sets, we’d have used Set has() in place of Array includes():

JavaScript
function getDifference(setA, setB) { return new Set( [...setA].filter(element => !setB.has(element)) ); } const set1 = new Set([1, 2, 3, 4]); const set2 = new Set([2, 4]); console.log(getDifference(set1, set2)); // {1, 3}

Get symmetric difference between two arrays

The method above only gives the methods in the second array that aren’t in the first:

JavaScript
function getDifference(arrA, arrB) { return arrA.filter((element) => !arrB.includes(element)); } const arr1 = [1, 3]; const arr2 = [1, 3, 5, 7]; console.log(getDifference(arr1, arr2)); // []

You want this sometimes, especially if arr2 is meant to be arr1‘s subset.

But other times you may want to find the symmetric difference between the arrays; regardless of which one comes first.

To do that, we simply merge the results of two getDifference() calls, each with the order of the arrays reversed:

JavaScript
function getDifference(arrA, arrB) { return arrA.filter((element) => !arrB.includes(element)); } function getSymmetricDifference(arrA, arrB) { return [ ...getDifference(arrA, arrB), ...getDifference(arrB, arrA), ]; } const arr1 = [1, 3]; const arr2 = [1, 3, 5, 7]; console.log(getSymmetricDifference(arr1, arr2)); // [5, 7] console.log(getSymmetricDifference(arr2, arr1)); // [5, 7]

How to get the difference between two sets in JavaScript

Get asymmetric difference between two sets

To get the difference between two sets in JavaScript, use the Array filter() and Set has() methods like this:

JavaScript
function getDifference(setA, setB) { return new Set( [...setA].filter(element => !setB.has(element)) ); } const set1 = new Set([1, 2, 3, 4]); const set2 = new Set([2, 4]); console.log(getDifference(set1, set2)); // {1, 3}

The Set has() method returns true if the Set contains a particular element and returns false if it doesn’t.

JavaScript
const arr = ['a', 'b', 'c']; const set = new Set(arr); console.log(set.has('a')); // true

Array filter() runs a callback on every element of an array and returns an array of elements that the callback returns true for.

JavaScript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const evenNumbers = numbers.filter( (number) => number % 2 === 0 ); console.log(evenNumbers); // [2, 4, 6, 8, 10]

The spread syntax (...) converts the set to an array for filter() to work.

The Set() constructor converts the result of filter() back to an Set.

Get symmetric difference between two sets

The method above only gives the elements in the second set that aren’t in the first.

JavaScript
function getDifference(setA, setB) { return new Set( [...setA].filter((element) => !setB.has(element)) ); } const set1 = new Set([2, 4]); const set2 = new Set([1, 2, 3, 4]); // Every item in set1 is also in set2, but the sets are different console.log(getDifference(set1, set2)); // {}

Sometimes you want this, especially if set2 is supposed to be a set1‘s subset.

But other times you may want to find the symmetric difference between the sets, regardless of which one comes first.

To do that, we simply merge the results of two getDifference() calls, each with the order of the Sets reversed.

JavaScript
function getDifference(setA, setB) { return new Set( [...setA].filter((element) => !setB.has(element)) ); } function getSymmetricDifference(setA, setB) { return new Set([ ...getDifference(setA, setB), ...getDifference(setB, setA), ]); } const set1 = new Set([2, 4]); const set2 = new Set([1, 2, 3, 4]); console.log(getSymmetricDifference(set1, set2)); // {1, 3} console.log(getSymmetricDifference(set2, set1)); // {1, 3}

How to easily detect when the mouse leaves the browser window in JavaScript

Detecting when the mouse leaves the browser window helps to track user engagement and display custom messages or popups.

Let’s learn how to do it with JavaScript.

Detect browser window mouse exit

To detect when the mouse leaves the browser window, use the mouseleave event listener:

index.html
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> <link rel="icon" href="favicon.ico" /> </head> <body> <div id="notifier"></div> <button class="btn-1">Be amazing</button> <script src="index.js" /> </body> </html>
index.js
document.addEventListener('mouseleave', () => { document.querySelector('#notifier').textContent = "Don't leave me!"; });

The mouseleave event fires on an Element when the mouse exits its bounds.

You can also use document.body to listen for when the user exits the window, but the body needs to be as big as the viewport for this to work:

index.js
document.addEventListener('mouseleave', () => { document.querySelector('#notifier').textContent = "Don't leave me!"; });
index.html
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> <link rel="icon" href="favicon.ico" /> <style> /* Makes body as big as viewport */ html, body { margin: 0; height: 100%; width: 100%; } </style> </head> <body> <h2>Welcome fellow developer</h2> <div id="notifier"></div> <script src="index.js"></script> </body> </html>

Using document.body over document could be better for compatibility with later Firefox versions.

Detect when user about to exit webpage

This helps to display an exit-intent popup, usually shown when the user is about to close the webpage or go to another.

Since tabs are usually at the top of the browser, we’d detect when the mouse leaves the browser window, but only from the top:

index.js
document.addEventListener('mouseleave', (event) => { if (event.clientY <= 0) { document.querySelector('#notifier').textContent = 'Have a good day!'; } });

clientY will be 0 at the very top of the viewport, so any higher and our if block’s code runs.

index.html
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> <link rel="icon" href="favicon.ico" /> </head> <body> <h2 id="notifier"></h2> <div> Welcome to Coding Beauty, a site for all things coding. </div> <script src="index.js" /> </body> </html>

How to easily fix the “Cannot read property ‘classList’ of null” error in JavaScript

The “Cannot read property ‘classList’ of null” error happens in JavaScript when you try to access the classList property on an element that isn’t in the HTML DOM.

Let’s look at various ways to quickly fix this error.

Fix: Ensure correct selector

To fix the “Cannot read property ‘classList’ of null” error in JavaScript, ensure the correct selector accesses an existing HTML element.

HTML
<div>Welcome to Coding Beauty</div> <button class="btn-1">Be amazing</button>

Check for any mistakes in the selector symbols in the script. Check for any mistakes in the ID or class name in the HTML tag. Maybe you forgot to set that id or class attribute at all?

JavaScript
// forgot the '.' symbol used for class selectors const button = document.querySelector('btn-1'); console.log(button); // 👉️ undefined // ❌ Uncaught TypeError: Cannot read properties of undefined (reading 'classList') button.classList.add('active');

Fix: Ensure DOM load before .classList access

The “Cannot read property ‘classList’ of undefined” error also occurs when you try to access .classList on an element that the browser hasn’t added to the DOM yet.

Maybe because your <script> is in the <head> tag and executes before the element’s parsing:

HTML
<!DOCTYPE html> <html lang="en"> <head> <title>Coding Beauty Tutorial</title> <!-- ❌ Script is run before button is declared --> <script src="index.js"></script> </head> <body> <div id="element"> console.log('Easy answers to your coding questions and more...'); </div> </body> </html>

The script tag is placed in the <head> tag above where the div is declared, so index.js can’t access the div.

index.js
const element = document.querySelector('.element'); console.log(element); // 👉️ undefined // ❌ Uncaught TypeError: Cannot read properties of undefined (reading 'classList') element.classList.add('highlight');

Solution: Move script to bottom

To fix the error in this case, move the script tag to the bottom of the body, after all the HTML elements have been declared.

HTML
<!DOCTYPE html> <html lang="en"> <head> <title>Coding Beauty Tutorial</title> </head> <body> <div id="element"> console.log('Easy answers to your coding questions and more...'); </div> <!-- ❌ Script is run after element is added to the DOM --> <script src="index.js"></script> </body> </html>

Now index.js will have access to the div and all the other HTML elements, because the browser would have rendered them by the time the script runs:

index.js
const element = document.querySelector('.element'); console.log(element); // 👉️ undefined // ✅ Works as expected element.classList.add('highlight');

Solution: Access .classList in DOMContentLoaded event listener

Another way to fix the “cannot read property ‘addEventListener’ of null” error is to add a DOMContentLoaded event listener to the document and access the element in this listener.

HTML
<!DOCTYPE html> <html lang="en"> <head> <title>Coding Beauty Tutorial</title> <!-- Script placed above accessed element --> <script src="index.js"></script> </head> <body> <div id="element"> console.log('Coding is more than a means to an end...'); </div> </body> </html>

The DOMContentLoaded event fires when the browser fully parses the HTML, whether or not external resources like images and stylesheets have loaded.

So regardless of where we place the script, the code in the listener only runs after every element is active in the DOM.

index.js
const element = document.querySelector('.element'); console.log(element); // 👉️ undefined // ✅ Works as expected element.classList.add('highlight');