"Encountered an error while trying to access properties that

Struggling to create a practice menu with the functionality of making elements appear and disappear on click? If you are encountering issues with a class named "option" not working as expected, you are not alone. Clicking on nested objects like images or icons might throw errors related to undefined properties. Despite logging the outerHTML of the clicked object successfully, adding a class becomes problematic. As a beginner in web development, any guidance, even if it only points me in the right direction, is greatly appreciated:)

let counter = 0;
const icon = document.querySelector('.dropdown-arrow');
const allIcon = document.querySelectorAll('.dropdown-arrow');
const options = document.querySelectorAll(".option");
const foodItem = document.querySelectorAll('.food-item')
const optionContainer = document.querySelectorAll('.option-container');

options.forEach(function(option) {
  option.addEventListener("click", function(event) {
    let element = event.target;
    let currentArrow = element.getElementsByTagName('ion-icon')[0];
    if (counter == 0) {
        // ARROW CLASS FUNCTIONALITY ON CLICK
        console.log(currentArrow.outerHTML);
        currentArrow.classList.add('rotate-on');
        currentArrow.classList.remove('rotate-off');
        counter++;

        //MENU DESC. FUNCTIONALITY
        foodItem.forEach(function(food) {
            food.classList.remove('hidden');
        })
    } else {
        // ARROW CLASS FUNCTIONALITY ON CLICK
        currentArrow.classList.add('rotate-off');
        currentArrow.classList.remove('rotate-on');
        counter--;
        
        //MENU DESC. FUNCTIONALITY
        foodItem.forEach(function(food) {
            food.classList.add('hidden');
        })
    }
  });
});
.rotate-on {
  transform: rotate(-180deg);
  transition: all .3s;
}

.rotate-off {
  transform: rotate(0deg);
  transition: all .3s;
}

.hidden {
  display: none;
}
<section class = "section section-menu">
    <!-- Including dummy content for clarity -->
</section>

Answer №1

The reason for this issue is that your element is not behaving as expected, as it is nested within another element. One way to resolve this problem is by preventing click events on inner elements and ensuring the click event triggers on the parent element (option) instead.

.title,
.option-container {
  pointer-events: none;
}

Alternatively, you can verify if the click event occurs inside the option element in JavaScript:

let clickedElement = event.target;
if(clickedElement.closest('.option')) clickedElement = clickedElement.closest('.option');

Once you have identified the correct element, you can then select the closest option.

In my opinion, using the CSS solution is the preferable method.

You can experiment with both solutions in this CodePen test environment.

Answer №2

One important step is to wrap your javascript code that interacts with the DOM within a window event listener:

window.addEventListener('load', function() {
//...
});

This ensures that the DOM has finished loading before your code runs, preventing any issues with empty variables like options.

Additionally, using let element = event.target; can be problematic because event.target may not always be an option element. It could actually be something like option-text or img, depending on what you click on.

To solve this, replace let element = event.target; with let element = option; since option is already captured within the closure.

Answer №3

I encountered an error message indicating that properties of undefined cannot be read.

The error message should specify which line is causing the issue, providing crucial information for troubleshooting. It is essential to carefully analyze error messages.

I believe that it is not undefined, at least I think so.

Trust in the code - if something is considered 'undefined', then it truly is. The perceived behavior may not always align with the actual value (such as with currentArrow).

Instead of making assumptions about the value, it's better to directly check by using console.log(currentArrow). If currentArrow is not undefined, the error may be caused by other factors.

Answer №4

If you console.log the variable

currentArrow = element.querySelector('ion-icon');
outside of the conditional statement, you will notice that it returns as UNDEFINED. It is advised to eliminate the usage of ".querySelector('ion-icon')" in order to achieve a more accurate output since 'element' does not possess that particular property.

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 recommended to use Promise.await over async/await?

After starting some new operations in my project, I discovered that db.aggregate needed to be executed asynchronously: db.aggregate( [ { $match: { "records": { $e ...

Enhancing Vue.js functionality with extra information stored in local storage

I've created a To Do List app where you can add tasks using a button. Each new task is added to the list with a checkbox and delete button in front of it. I'm trying to save all the values from the inputs and the checked checkboxes on the page on ...

Troubleshooting a problem with the Jquery cycle plugin in HTML and CSS

Hi there! I've successfully integrated the jQuery cycle plugin into my slideshow, which is working great. However, I want to make the navigation controls (previous, next, pause, play) display as background images instead of visible text links. I' ...

Utilizing ng-model with invisible input field

UPDATED: Experimenting with a new approach: <input class="form-check-input deflog-check" type="checkbox" ngTrueValue = "1" ngFalseValue = "0" ng-value="chk_mail"> Now trying to retrieve the value in AngularJS like so: object2Edit.notification = N ...

Html content overlapping div rather than being stacked vertically

My goal is to arrange a group of divs inside another div in a vertical stack. However, I am facing an issue where the text from the last div is overlapping with the second div instead of following a proper vertical alignment where the text in the third div ...

Activate inactive html button using javascript

One of the challenges I am facing is testing forms where the client specifically requested that the submit button be disabled by default. I have been exploring ways to dynamically replace the disabled="" attribute with enabled using JavaScript within a s ...

CSS: What is causing my three columns to divide?

I am encountering CSS issues while attempting to develop a React app using Next.js. Here is the content of my home.module.css: .grid_container { /* display: grid; */ /* grid-template-columns: auto auto auto; */ /* column-count: 3; align-items: fle ...

Is there a way to dynamically access BEM-style selectors using CSS modules?

For instance, I have this specific selector in my App.module.css file: .Column--active I want to access this selector from the App.js file in React using CSS modules. After importing all selectors from the CSS file as import styles from './App. ...

Is there a way to automatically increase the input id when adding a new row?

I have been working on dynamically adding new inputs and trying to assign a new ID that increments by 1 each time I add a new input. However, I am facing an issue where the value is not incrementing as expected. Can someone please help me identify what&apo ...

Axios: Exception handling does not involve entering the catch method

Implementing a function to adjust a contract name involves making an axios request to the backend API using a specific ID. Upon each execution, a sweetalert prompt is displayed. axios({ url: '/api/contract/' + id, method: 'put ...

What is the best way to send an event handler to a sibling component?

I am facing a situation where I have an eventHandler that needs to be handled by its sibling component. The <Brains /> component contains several properties (such as this.randomNumber = 555 inside the constructor) that are required for the proper fun ...

Problems that seem to loop endlessly

I was working on some algorithm challenges from a coding platform, and I hit a roadblock with the "The Final Countdown" challenge. Here's what the challenge required: Provide 4 parameters (param1, param2, param3, param4), print the multiples of para ...

React throwing an error when attempting to include a Link component from react-router-dom

Currently working on a React app and encountering an issue while trying to add the Link component from the react-router-dom package. The main routes are defined in the App.js file structured as follows: https://i.stack.imgur.com/BF8M8.png The <Header ...

modify the navigation when router events are triggered

Is there a way to modify the destination route after the router events have been triggered in an Angular app? I am trying to implement a functionality where if the user clicks the browser back button, the navigation is redirected to the home page. However, ...

Importing multiple modules in Typescript is a common practice

I need to include the 'express' module in my app. According to Mozilla's documentation, we should use the following code: import { Application }, * as Express from 'express' However, when using it in TypeScript and VSCode, I enc ...

How to Prevent Scrolling When Modal is in Use on Full Page JS

I am trying to achieve the functionality where when the modal is open, I want to prevent full-page scrolling in JavaScript. The issue arises when I open the modal and try to scroll, it ends up moving the content that's behind the modal, which is actua ...

Ways to delete a tag with jQuery

Currently I'm struggling with hiding elements like delpc and picnam. Here is the structure of my code: <ul id="userpic" class="user pic"> <im class="pict"/> Picture preview </ul> <div id="showpicname"> <div id= ...

Have you checked the console.log messages?

As a newcomer to web development, I hope you can forgive me if my question sounds a bit naive. I'm curious to know whether it's feasible to capture a value from the browser console and use it as a variable in JavaScript. For instance, when I enco ...

Mocha: A Unique Perspective on Testing the express.Router Instance

As I was developing a JavaScript controller file, I came across the need to test if my controller instance contains an instance of the express method called Router(). import {assert} from 'chai'; import {UF_Controller} from '../../controlle ...

Unable to define an object within the *ngFor loop in Angular

In order to iterate through custom controls, I am using the following code. These controls require certain information such as index and position in the structure, so I am passing a config object to keep everything organized. <div *ngFor="let thing of ...