What steps can I take to help EventListener locate a specific class if it is experiencing difficulty?

In the process of creating a responsive navigation bar, everything seems to be functioning correctly except for a small javascript error that arises in my sub menu when clicking.

Despite thoroughly checking through my index, script, and style files, I am unable to pinpoint why the EventListener is returning null when trying to locate the specified class.

The HTML code from which I am attempting to select a class:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title> Uncle Jeffs Pack</title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <!-- Boxicons CSS -->
        <link href='https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f5f8effef4f8f9e4d7a5b9a6b9a3">[email protected]</a>/css/boxicons.min.css' rel='stylesheet'>

    </head>
    <body>
        <nav>
            <div class="navbar">
                <i class='bx bx-menu'></i>
                <div class="logo"><a href="#">UJP</a></div>
                <div class="nav-links">
                    <div class="sidebar-logo">
                        <span class="logo_name">UJP</span>
                        <i class='bx bx-x'></i>
                    </div>
                    <ul class="links">
                        <li><a href="#">HOME</a></li>
                        <li>
                            <a href="#">PHOTOS</a>
                            <i class='bx bxs-chevron-down arrow photos-arrow'></i>
                            <ul class="photos-sub-menu sub-menu">
                                <li><a href="#">Drop 1</a></li>
                                <li><a href="#">Drop 2</a></li>
                                <li><a href="#">Drop 3</a></li>
                                <li><a href="#">Drop 4</a></li>
                                <li class="more">
                                    <a href="#">More</a>
                                    <i class='bx bxs-chevron-right arrow more-arrow'></i>
                                    <ul class="more-sub-menu sub-menu">
                                        <li><a href="#">Drop 1</a></li>
                                        <li><a href="#">Drop 2</a></li>
                                        <li><a href="#">Drop 3</a></li>
                                        <li><a href="#">Drop 4</a></li>
                                    </ul>
                                </li>
                            </ul>
                        </li>
                        <li>
                            <a href="#">BLOGS</a>
                            <i class='bx bxs-chevron-down arrow blogs-arrow'></i>
                            <ul class="blogs-sub-menu sub-menu">
                                <li><a href="#">Drop 1</a></li>
                                <li><a href="#">Drop 2</a></li>
                                <li><a href="#">Drop 3</a></li>
                                <li><a href="#">Drop 4</a></li>
                            </ul>
                        </li>
                        <li><a href="#">ABOUT US</a></li>
                        <li><a href="#">CONTACT US</a></li>
                    </ul>
                </div>
                <div class="search-box">
                    <i class='bx bx-search-alt-2'></i>
                    <div class="input-box">
                        <input type="text" placeholder="Search...">
                    </div>
                </div>
            </div>
        </nav>
        <div class="main-paragraph">
            <h2>Hello World</h2>
        </div>
    <script src="script.js"></script>
    </body>
</html>

When implementing the following code into my script.js file, an error appears in the console: Cannot read properties of null (reading 'addEventListener)

let navbar = document.querySelector(".navbar");
let searchBox = document.querySelector(".search-box .bx-search-alt-2");

searchBox.addEventListener("click", ()=>{
    navbar.classList.toggle("showInput");
    if(navbar.classList.contains("showInput")){
        searchBox.classList.replace("bx-search-alt-2","bx-x");
    }else {
        searchBox.classList.replace("bx-x", "bx-search");
    }
});

// sidebar open close js code
let menuOpenBtn = document.querySelector(".navbar .bx-menu");
let closeOpenBtn = document.querySelector('.nav-links .bx-x');
let navLinks = document.querySelector(".nav-links");

menuOpenBtn.addEventListener("click", ()=>{
    navLinks.style.left="0";
});
closeOpenBtn.addEventListener("click", ()=>{
    navLinks.style.left="-100%";
});

Following some research, I have discovered that this issue may occur due to the script running before the DOM is fully loaded. I have attempted using "window.onload=function()" but the problem persists. Any assistance would be greatly appreciated. Thank you.

Answer №1

Robo Robok is spot-on. He beat me to the punch with his mention of ".photos-arrow"

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

Uploading multiple images using Cordova's File Transfer feature

Working on a project using Cordova and jQuery Mobile, my goal is to upload multiple images with the file transfer plugin. After successfully uploading one image, I am now attempting to upload 2 or 3 images in succession. Below is the HTML code snippet: ...

How to directly stream a Google Cloud Storage file into an fs.Readstream without the need to save it

Is there a way for me to send a video file directly from Google Cloud Storage to an API that only accepts fs filestreams without having to download and save the file locally first? I'm currently using the code below to send video files, but it require ...

CSS can be utilized to craft intricate and dynamic shapes

Currently, I am attempting to produce a trapeze-like design utilizing various techniques in order to achieve the best possible outcome. The shape I am aiming to create is similar to this: (the content inside the shape will consist of images and text) Th ...

CodeIgniter Flexi Auth - Redirect users promptly upon login expiration

Is it possible to use the CodeIgniter Flexi Auth library to redirect a user to the login page immediately upon session expiration, displaying a message stating: "Your login has expired, please login again," rather than waiting until page load? I'm co ...

Retrieve the text from an ajax response that includes the <tag> element

I have created a simple piece of code to fetch news from an RSS page. Below is the code snippet: this.loadRecentNews = function loadRecentNews() { $.get("http://rss.nytimes.com/services/xml/rss/nyt/GlobalHome.xml", function (data) { ...

Learn how to move to a new line when inputting data into a CSV file with JavaScript

My challenge involves taking an array of objects, for example: array=[hello, how, are, you], extracted from the document.innerHTML. I aim to write these objects to a CSV file using puppeteer and JavaScript, each on a new line. Although when using the sta ...

One jQuery plugin was functioning perfectly, while the other one was failing to work as expected

I am working on a simple HTML file that includes a heading and two empty div elements. <h1>Blablabla.</h1> <div id="div1"></div> <div id="div2"></div> These two divs need to be populated with SVG content generated usin ...

What is the best way to guide a user to a specific page based on the choice they made after submitting a form?

My form includes a list of 6 options where users can only select one. After submitting the form, I want to redirect them to a specific page based on their selection. For example, I have the following 3 options: Facebook Youtube Twitter If a user selects ...

Styling Your Navigation Bar with CSS and Active States

Creating an interactive navigation element for a menu can be challenging, but here's a helpful example. http://jsfiddle.net/6nEB6/38/ <ul> <li><a href="" title="Home">Home</a></li> <li class="activ ...

How to showcase numerous PDF documents within a ReactJS application

As a newcomer to the world of React, I am facing an issue with displaying multiple PDFs based on the selected link. Although I have been successful in displaying a PDF from a list of links pointing to my stored PDFs within the src directory, I encounter th ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

Guide on invoking a node.js function from an express-rendered ejs page

My express server currently has a button that triggers a POST request to activate a function in my node.js server. Instead of using a traditional POST request, I am interested in implementing something like AJAX so that the page doesn't reload. Is th ...

Leveraging Prisma Client alongside Supabase Edge Functions

I encounter an issue when trying to integrate the generated @prisma/client with Supabase Edge functions. Running npx prisma generate places the client in the default location within my node_modules folder, inaccessible for edge function usage. To resolve t ...

How to make background color transparent in CSS for Safari browser

Does anyone know how to make the background color transparent in Safari? Right now, my PNG file is showing with a white background instead of being transparent. I have attempted: background-color: transparent; background-color: rgba(255,255,255,0); appe ...

Issues encountered while attempting to convert HTML Image and Canvas Tags to PDF within Angular 2

I am currently facing an issue with my code. My requirement is to download HTML content as a PDF file. I have been successful in downloading text elements like the <p> tag, but I am encountering difficulties when trying to download images and canvas ...

A guide on how to implement promise return in redux actions for react native applications

I'm using redux to handle location data and I need to retrieve it when necessary. Once the location is saved to the state in redux, I want to return a promise because I require that data for my screen. Here are my actions, reducers, store setup, and ...

Using Typescript to establish a connection between ngModel and an object's property

Let's talk about how we can dynamically bind an input to an undefined property in an object. For example, we have an object named user: let user = {}; How can we bind an input to a property that doesn't exist yet? Like this: <input [(ngMode ...

How to deselect a checkbox using AngularJS

I have a checklist of items <input type="checkbox" ng-model="servicesModel" value={{item.name}} id={{item.name}} ng-click="toggleSelection(item.name)"/> and I need to unselect the currently selected checkbox $scope.toggleSelection = function toggl ...

Hiding elements in HTML with React when data is null

Is there a way to hide elements using classes like "d-none" when the data is null in React? <span className="product__tag">{prod.tag1}</span> <span className="product__tag">{prod.tag2}</span> <span classN ...

Looking for guidance on sending data from a JS file to HTML using Nodejs? Seeking advice on various modules to achieve this task effectively? Let's

Looking for advice on the most effective method to transfer data from a JS file (retrieved from an sqlite db) to an HTML file in order to showcase it in a searchable table. My platform of choice is NodeJS. As a beginner, I am willing to put in extra time a ...