"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

Different ways to swap table cells using only CSS

Does anyone know how to switch the positions of table cells using only CSS? I have three divs set up like this: #content { width: 1000px; display: table; float: none; vertical-align: top; border: 1px solid red; } #left { float: left; } #ri ...

What is the process for displaying a list of all files within a folder?

I'm currently working on a project where I have a 'products' directory located in the same folder as my index.html file. My goal is to develop a script that can tally all the jpg files within the 'products' folder and then generate ...

How to add a line break within the :after pseudo-element using CSS

I've been struggling to split text inside an :after pseudo-element of a label that receives its content from a data- attribute. I've attempted using word-break, as well as playing around with width, max-width, and position:relative, but nothing s ...

One column in HTML table row is functional, while the other is not functioning as intended

Currently, I am working on a mapping application that allows users to add features to a database. These features are then displayed on a mapping page in an HTML table. The table consists of three columns: Feature Name, Selected (with an on/off slider switc ...

Is it possible for an HTML number input's arrows to change in increments that are different from its designated step attribute?

Within my design, I have implemented an <input type="number" step="1"> element for selecting font size. However, in the context of working on a large canvas, adjusting the number by 1 is hardly noticeable. It would greatly enhance ...

Encountering a problem with Chrome Extension localization upon installation - receiving an error message claiming default locale was not specified, despite having

Error Message: "The package has been deemed invalid due to the following reason: 'Localization was utilized, however default_locale was not specified in the manifest.' Issue: I have developed a customized extension and defined a default locale, ...

Personalized service implemented in Angular's .config settings

I've come across a few examples of how to insert custom providers into angular's .config, but I'm struggling to do it correctly. Here's the provider I have: (function() { var app = angular.module('application.providers', [& ...

what is the best way to change background image in media query for various screen sizes?

I have a customized email template with a background image. The size of the image is 600px (width), and I have applied a class called back-img for styling purposes. I am looking to override this class specifically for all mobile screen sizes, including lan ...

Today's feature dish

I have scoured numerous tutorials online, but none of them seem to solve my issue. Currently, I have these buttons: <a href='faq.php'><div class='button'> <div class='button_top'> </div> <div class ...

Guide to turning off the pinch-zoom feature on Windows 8 laptops

I'm currently working on a Windows 8 desktop application where I am using C#, JavaScript, and HTML5. Specifically in the C# portion, I am utilizing the WebView object. My goal is to disable pinch-zoom within my application. I already know how to achi ...

Using object bracket notation in TypeScript to retrieve values from props with the help of string interpolation

I encountered an issue in my code while attempting to utilize a variable within my TSX component. This problem arises due to the dynamic props being passed into the component, which are always a string that matches one of four keys in the "characters" obje ...

AngularJS: Utilizing angular-filter for grouping by two columns

I may come across as a bit confusing, so please allow me to clarify. Note: An operational piece of code (POC) has been included with this post. I have an array of objects with 3 properties: name name team team_rank $scope.players = [ {name: & ...

How do I set the initial state to a specific node in xstate?

I'm currently working on a multi-step form that guides users through selecting services, providing contact information, and entering billing details. I have implemented a progress bar and event emissions to track the user's current step using xst ...

Tips for positioning an advertisement at the center of a full-screen HTML5 game

I am struggling to find a way to perfectly center my advertisement in a fullscreen HTML5 game. The game automatically expands to fullscreen when played, and I want the advertisement to always be positioned in the center, regardless of whether the game is b ...

Exploring the attributes of div elements with XPath

Currently, I am in the process of familiarizing myself with xpath through the creation of a basic program that will display the list of Premier League fixtures in football from a specific webpage. The page in question can be found at the following link: A ...

How to incorporate sound files in JavaScript

I have a collection of small audio files that I want to play sequentially, not all at once. To do this, I am using the Audio object in JavaScript as shown below: var audio_1 = new Audio(); var audio_2 = new Audio(); var audio_3 = new Audio(); audio_1.src ...

Are cross-browser gradients causing performance problems for browsers?

Although I attempted to tag this question as [subjective] (without success), I understand that it may be unanswerable, involve common knowledge that I can't find, or simply be a matter of opinion. Over the past few months, I have been creating commer ...

Struggling to center a MatIcon within a MatButtonToggle component in an Angular project

I've been struggling to center the MatIcon in the MatButtonToggle, trying multiple methods without success. It may seem like a minor issue, but it's causing quite a bit of trouble for me. Can someone please guide me on how to make this adjustment ...

Are user message templates available for use with Twitter Bootstrap?

I am interested in implementing Twitter Bootstrap into my website design. While it looks amazing, I now need to incorporate user messages (similar to those found on forums or Twitter). These messages should include short text, submission time, user image, ...

Difficulty with positioning two divs side by side in HTML/CSS?

Hey there, I'm facing some strange CSS issues while trying to achieve a specific layout. I want to have a warning icon on the right side of each input field, which are horizontally centered: https://i.sstatic.net/IY3xp.png Currently, I have managed ...