Accordion menu drop down is functional only for the initial drop down option

Looking to incorporate a straightforward accordion drop-down menu using basic HTML and JS. The following presents the relevant JS, CSS, and HTML code.

var heading = document.getElementsByClassName("drop_title");
var headingNumber = heading.length;

for (var i = 0 ; i < headingNumber; i++) {
    heading[i].addEventListener("click", () => {
        document.querySelector('.accordion_box li ul').classList.toggle('drop_list')
    });
}
.accordion_box {
    background: #004d7a;
    font-family: 'Zen Kaku Gothic Antique', sans-serif;
    color: white;
    box-shadow: rgba(0, 0, 0, 0.15) 1.95px 1.95px 2.6px;
    width:50%;
    margin-top: 25%;
}

.accordion_box ul li {
    list-style-type:none;
}

.drop_title {
    font-size:17px;
    padding:0 10px;
}

.drop_title:hover{
    border-left: 5px solid #a8eb12;
    border-bottom: 5px solid #a8eb12;
}

.accordion_box ul ul li a{
    color:white;
    font-size:14px;
    text-decoration:none;
}

.accordion_box ul ul li a:hover{
    border-left: 5px solid #a8eb12;
}

.drop_list{
    display:none;
}

.accordion_box li.active ul{
    display:block;
    transition: all 2s ease-in-out;
}
<div class="accordion_box">
    <ul>
        <li>
            <h3 class="drop_title">Menu One</h3>
            <ul class="drop_list">
                <li><a href="#">One</a></li>
                <li><a href="#">Two</a></li>
                <li><a href="#">Three</a></li>
            </ul>
        </li>
        <li>
            <h3 class="drop_title">Menu Two</h3>
            <ul class="drop_list">
                <li><a href="#">One</a></li>
                <li><a href="#">Two</a></li>
                <li><a href="#">Three</a></li>
            </ul>
        </li>
        <li>
            <h3 class="drop_title">Menu Three</h3>
            <ul class="drop_list">
                <li><a href="#">One</a></li>
                <li><a href="#">Two</a></li>
                <li><a href="#">Three</a></li>
            </ul>
        </li>
        <li>
            <h3 class="drop_title">Menu Four</h3>
            <ul class="drop_list">
                <li><a href="#">One</a></li>
                <li><a href="#">Two</a></li>
                <li><a href="#">Three</a></li>
            </ul>
        </li>
    </ul>
</div>

After clicking on Menu One, I can toggle its list display, but oddly when selecting any other title, it collapses Menu One instead of revealing the correct associated list. What am I missing here?

I'd appreciate some guidance on this matter.

Answer №1

If you're looking to apply a click event to all elements using forEach, you need to pass a parameter in the function and then add the click event based on that parameter. You can then select the parent element using the parameter and toggle the class of the desired element.

Check out the code snippet below:

var heading = document.querySelectorAll(".drop_title");
var headingNumber = heading.length;

heading.forEach(function(el) {
    el.addEventListener("click", function() {
       el.parentNode.querySelector('.accordion_box li ul').classList.toggle('drop_list');
   });
});
.accordion_box {
    background: #004d7a;
    font-family: 'Zen Kaku Gothic Antique', sans-serif;
    color: white;
    box-shadow: rgba(0, 0, 0, 0.15) 1.95px 1.95px 2.6px;
    width:50%;
    margin-top: 25%;
}

.accordion_box ul li {
    list-style-type:none;
}
// Additional CSS styles here
<div class="accordion_box">
    <ul>
        // HTML content here
    </ul>
</div>

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

Encountering an issue while trying to verify user registration in MySQL using Node.js Express. During the user registration process, an error arises indicating that 'res' is not defined

import React from 'react' import { Link } from 'react-router-dom' import {useNavigate} from 'react-router-dom'; import { useState } from 'react' axios from "axios" const Register = () => { const [i ...

Determine the total value derived from adding two option values together

I am attempting to calculate the sum of two select options and display the result. So far, my attempts have only resulted in returning the value 1. What I am aiming for is to add the values from n_adult and n_children, and then show the total under Numbe ...

Testing AJAX requests across different domains on a local server setting

While working in my local development environment at , I encountered the need to make an Ajax call to open a URL and display the response in fancybox. Due to the local development environment, this creates a cross-domain issue. However, once deployed to ...

managing commitments in TypeScript

Is there a way to convert a promise into a string, or is there another method for handling this result? I am encountering an error stating "You cannot use an argument of type 'Promise' for a parameter of type 'string'." const pokemonIma ...

Troubleshooting Angular 4's ng-selected functionality

I'm currently facing an issue with getting ng-selected to function properly. Initially, I attempted to simply add selected in the option tag, but later discovered that I should be using ng-select. Despite trying variations such as ng-selected="true" a ...

Having trouble with the $.get function in AJAX with Rails 4? It seems

After working with Rails for a few years, I decided to dip my toes into the world of AJAX. With a Rails 4 app in hand, I'm currently testing out some functions. My end goal is to reload a partial on the edit page located at app/views/stories/edit.html ...

Is there a way to assign retrieved data to the $scope.variable?

I'm relatively new to both JavaScript and Angular. I have a piece of code that fetches data from an API and successfully prints it to the console, but I'm facing issues when trying to assign this data to $scope.saveData. It seems to only work wit ...

Having trouble running "npm install" after cloning a React project from GitHub?

I am currently using Ubuntu 20.04.4 LTS and attempting to set up a React project locally. After cloning the repository from GitHub and trying to install the react app locally using the following commands: git clone https://github.com/OpenClassrooms-Stude ...

Pass data from the view to the controller in CodeIgniter using an array

Take a look at: user_data received from the controller (Database middleware values) <?php $ID['IDS'] = array_column($user_data, 'ID'); print_r($ID); // print_r($ID)=Array( [IDS] => Array([0] => 0 [1] => ABC ...

What is the method for incorporating dates as values and on the X axis within RGraph?

I have been experimenting with the horizontal bar RGraph demo using this code and have found it to be very successful: let newData = [1, 40, 30]; let hBarChart = new RGraph.HBar('myCanvas', newData); hBarChart.Set('chart.labels', [&apo ...

I need to know how to send a "put" request using JavaScript and Ajax

My task involves programmatically updating a spreadsheet using my code. I am able to write to a specific cell within the spreadsheet with the following function: function update(){ jQuery.ajax({ type: 'PUT', ...

Sideways scrolling carousel/slider

Currently, I am in the midst of a project page where my aim is to incorporate a horizontal scrolling project/image slider. Strangely enough, all my attempts thus far have failed to produce the desired outcome. This is the layout: the projects must transit ...

Choose the OK button on the modal during the testing phase

I am having difficulty selecting an element on my webpage using testcafe because I am not very familiar with selectors. I am open to choosing it in the JSX or HTML, but I am struggling with both methods. Once I click the "LayerAddingPopUpButton", a modal a ...

The challenge in displaying data from the backend using ajax in Vue.js 2.0 is hindering its visibility on the view

Currently, I am utilizing vue.js version 2.0, and the demo provided below is fully functional. <div class="container" id="app"> <ol> <li v-for="(todo,index) in todos"> {{ index }} {{ todo.text }} </li&g ...

different ways to analyze elements within the identical array of objects

Currently, I am developing a method for a website that can compare elements within a JSON array of objects. For example: [ { course code: act 227, course name:science, section:12345, statues:closed, day : 1 3 5, ...

Viewing margins displayed differently in Chrome compared to Firefox and making corrections accordingly

Why is the margin not displaying correctly? I noticed a 4px difference in Chrome in the box_news element. I read something about rest.css but I'm not sure if it will be helpful in my situation. This is the code on the right side: <div class="righ ...

Error Encountered: Bootstrap Dropdown Menu Malfunction in Master Page

I'm struggling to make my Bootstrap drop down menu function properly. Nothing happens when I click on the link, no dropdown appears. I've set up my nav bar in a master page and have spent hours trying to troubleshoot it without success... This i ...

Why do static files in Node.js + Express.js on Windows take up to two minutes to load?

I'm encountering an issue in my Windows environment with Node.Js/Express.js where static JS files can sometimes be labeled as 'pending' in the browser (even with caching disabled) for up to two minutes before finally downloading successfully ...

Having trouble getting past the "Starting metro bundler" step when using the 'expo start' or 'npm start' command?

Currently, I am using React Native Expo to develop a mobile application. The process I followed includes the following steps: expo init myapp cd myapp expo start Initially, everything was running smoothly after executing these three commands. However, as ...

renewing a div element without the need to reload the entire webpage

I'm currently developing a setup process for configuring a database. My goal is to allow the user to progress through each phase without having to refresh the page. However, I've encountered an issue while trying to implement the .load() function ...