Display a dropdown menu when clicking on a close button in a single element using Vanilla JavaScript

I'm currently in the process of learning Javascript and trying to grasp the concept of events and selectors.

My aim is to have a close button that, when clicked, triggers a specific dropdown related to the card it's attached to.

I plan to achieve this by toggling a class where the necessary styles have already been defined.

The issue I'm encountering is as follows: Uncaught TypeError: Cannot read property 'classList' of undefined;

If I use a standard event handler, all dropdown menus are affected, which is not the desired outcome.

Below is my code:

HTML

    <section id="wrapper">
    // HTML content here
</section>

CSS

<pre>
    /* CSS styling here */
</pre>

Javascript

(function() {
    let closeButtons = Array.prototype.slice.call(document.querySelectorAll(".close"));
    closeButtons.forEach(function(button) {
        button.addEventListener("click", function(e) {
            let elements = Array.prototype.slice.call(document.querySelectorAll('ul'));
            elements.forEach(function(e) {
                e.target.classList.toggle('show');
            });
        });
    });
})();

Could someone provide insight on what might be going wrong, and offer suggestions for fixing the script to reach the intended result?

Note: Using jQuery is not an option.

Answer №1

If you want to only toggle the ul element within the same figure as the button that was clicked, you can use this code:

button.addEventListener("click", function() {
  let figure = this.parentNode; // find the surrounding figure element of the clicked button
  let targetUL = figure.querySelector("ul"); // locate its ul element
  targetUL.classList.toggle("show");
});

This code snippet can be simplified to:

button.addEventListener("click", function() {
  this.parentNode.querySelector("ul").classList.toggle("show");
});

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

Invoking a greasemonkey script when a user interacts with a button

For a script I wrote, I added an extra column and link in each row. However, the issue is that I want the links to trigger a function in my greasemonkey script and pass a variable to it. I have learned that because greasemonkey operates in a sandbox, achi ...

Center the content of the HTML body

Despite my best efforts, I seem to be making a mistake somewhere. While creating a bootstrap website at , the site appears well and aligned in the center. However, when I try to adjust the screen size to less than 850px or even smaller, all the content shi ...

Ways to send user input to a function within a React component

I am currently working on implementing a simple feature where users can search posts by their tags. To achieve this, I have created the Feed.jsx component with the following code: "use client"; import { useState, useEffect } from "react&quo ...

Adjusting various settings on breakpoints in MUI v5

Previously in MUI version 4, I was able to apply multiple style parameters within a single media query using the following code: [theme.breakpoints.up('xs')]: { width: 100px, color: green, }, [theme.breakpoints.up('md' ...

Tips on swapping out a part in ExtJS

Currently, my ExtJS window features a toolbar at the top and loads with a plain Panel at the bottom containing plain HTML. Everything is working smoothly in this setup. However, I now wish to replace this bottom panel (referred to as 'content') w ...

Creating a form in NextJS to securely transfer user input data to MongoDB

Being new to JavaScript, I have a basic understanding and some lack of experience, but I am eager to learn more. Recently, I embarked on a project using NextJS, an efficient framework that integrates with ReactJS. My current challenge lies in creating a si ...

Arranging individual spans within a div using CSS for perfect alignment

My current code looks like this: <div id='div_selectores' class='row_titulo '> <span class="label_selector" id="lbl_show"></span><span id="div_selector_show"></span> <br /> <span class ...

Modify Knockout applyBindings to interpret select choices as numeric values

Utilizing Knockout alongside html select / option (check out Fiddle): <select data-bind="value: Width"> <option>10</option> <option>100</option> </select> Upon invoking applyBindings, the options are interprete ...

Adjusting the height of a card in Reactstrap

I am currently exploring Reactstrap and aiming to ensure a specific Card adjusts according to the size of the window by setting its aspect ratio using percentages rather than pixels. Interestingly, while adjusting the width works as desired, I'm faci ...

Converting javascript html object lowercase

Is there a way to dynamically adjust the height of specific letters in my label? Right now, I am overriding the text for the elements: let element = document.getElementById('xxx') element.textContent = 'Label' I attempted using <sup ...

Issue: Unable to open port (GetCommState) : Error code 1 not recognized - Utilizing Nodejs, express, SerialPort

I am currently attempting to establish a connection between a fiscal printer with serial input and nodejs. I am utilizing the SerialPort module, but encountering difficulty in establishing the connection. The console is displaying the following error messa ...

In my current Next.js project, I tried setting up a new [collectionId].jsx file within the pages directory, but I am facing issues with getting

In my current next.js project, I recently created a file named [collectionId].jsx within the pages directory. Interestingly, I noticed that Tailwind CSS does not seem to work properly with this file. However, when I renamed the file to [collectionId].js wi ...

Is there a method to retrieve the bounds (northeast and southwest) of the map display when there is a change in the bounds, center, or view area?

In my NextJs project, I am utilizing the TomTom Map SDK to implement a feature where, upon loading the map based on its bounds, I query for nearby restaurants in that specific area. Additionally, when there are zoom or drag events on the map, I want to mak ...

The null error occurs when rendering with React's state array

When I try to call an API that emits JSON, I am encountering an issue. I call the promise API function in componentDidMount, set the state, and then call it in the render method, but it always returns a null error. I need assistance, please. Interface fo ...

What are the steps to effectively utilize <ul> for showcasing scrolling content?

I stumbled upon and found it to be a great inspiration for my project. I tried replicating the layout of the listed items on the site: .wrap { display: block; list-style: none; position: relative; padding: 0; margin: 0; border: ...

Customized style sheets created from JSON data for individual elements

One of the elements in the API requires dynamic rendering, and its style is provided as follows: "elementStyle": { "Width": "100", "Height": "100", "ThemeSize": "M", "TopMargin": "0", " ...

Performing a MongoDB query in a controller using the MEAN stack with Node.js

My goal with this controller is to retrieve all the results of a collection. Despite having one item in the prop collection, I am encountering an undefined error. Error: Cannot call method 'find' of undefined This snippet shows my server.js fil ...

Tips for effectively passing query string parameters in Angular

I am looking to make an HTTP request with parameters through a query For instance: URL: https://api/endpoint?d=1&value=2 ...

Why is my HTML image stored in the database not showing up in TCPDF?

Currently, my situation involves using TCPDF to retrieve content from a MySQL table row that contains HTML code like this: <p><a href="x.html"><img src="http://1/2/3/x.jpg" width="x" height="x"></a></p> The problem arises wh ...

Changing focus to 'DIV' element without JQuery using Javascript and Angular's ng-click event

Instructions for using an Angular directive to set focus on a "DIV" element when clicked <a href="#" class="skipToContent" ng-click="showContent()" title="skip-to-main-content">Skip To Main Content</a> <div class="getFocus" role="button" ...