Recursively toggle child elements using JQuery

My knowledge of JQuery is limited, so here's the issue I'm facing. Below is an example of the HTML structure:

<ul class="first-class">
   <li class="second-class">
      <a href="#_">
        <i class="fa fa-plus"></i>
      </a>
      <ul class="subdirectory-class">
         <li class="second-class">
            <a href="#_">
              <i class="fa fa-plus"></i>
            </a>
            <ul class="subdirectory-class">
               <li class="second-class">
                  <a href="#_">
                     <i class="fa fa-plus"></i>
                  </a>
               </li>
            </ul>
         </li>
     </ul>
   </li>
   <li class="second-class">
      <a href="#_">
         <i class="fa fa-plus"></i>
      </a>
      <ul class="subdirectory-class">
         <li class="second-class">
            <a href="#_">
              <i class="fa fa-plus"></i>
            </a>
         </li>
     </ul>
   </li>
</ul>

What I want to achieve is toggling a specific subdirectory when clicking on the corresponding + sign icon. Currently, my JQuery code toggles all subdirectories at once. How can I modify the code to accomplish this?

The desired behavior is for only the next subdirectory to open/close when clicking on the respective + sign or subdirectory link. This sequence should continue as you progress through different levels of subdirectories.

JQUERY - My current implementation:

$(document).ready(function(){
    $(".first-class .second-class").click(function(e){
        $(".subdirectory-class", this).first().slideToggle("fast");
        $(this).children("a").toggleClass("closed open");
        e.preventDefault();
    });
});

The current code hides all ul elements except for the main one (initially set with display:none), toggling all subdirectories when clicking. Any assistance on improving this functionality would be greatly appreciated.

Thank you in advance

Answer №1

If you include e.stopImmediatePropagation() in your code, it will execute according to your needs.

$(document).ready(function() {
  $(".second-class").click(function(e) {
    $(this).find(".subdirectory-class").first().slideToggle("fast");
    $(this).children("a").toggleClass("closed open");
    e.stopImmediatePropagation()
  });
});

Demo

$(document).ready(function() {
  $(".second-class").click(function(e) {
    $(this).find(".subdirectory-class").first().slideToggle("fast");
    $(this).children("a").toggleClass("closed open");
    e.stopImmediatePropagation()
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="first-class">
  <li class="second-class">
    <a href="#_">1
      <i class="fa fa-plus"></i>
    </a>
    <ul class="subdirectory-class">
      <li class="second-class">
        <a href="#_">11
          <i class="fa fa-plus"></i>
        </a>
        <ul class="subdirectory-class">
          <li class="second-class">
            <a href="#_">111
              <i class="fa fa-plus"></i>
            </a>
          </li>
        </ul>
      </li>
    </ul>
  <li class="second-class">
    <a href="#_">2
      <i class="fa fa-plus"></i>
    </a>
    <ul class="subdirectory-class">
      <li class="second-class">
        <a href="#_">22
          <i class="fa fa-plus"></i>
        </a>
      </li>
    </ul>
  </li>
</ul>

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

The functionality of Bootstrap toggle ceases to operate properly following an AJAX content update

I am currently using AJAX load to fetch some content on my webpage. I am working with Bootstrap 3 and Bootstrap toggle. When the content is loaded, the Bootstrap 3 content functions properly (the panel-primary panel is clearly visible). However, the Bootst ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

Is there a way to determine if a user has the ability to navigate forward in Next.js?

I am faced with a challenge of determining whether a user can navigate forward on a webpage. My goal is to have two buttons - one to go back and another to go forward, with the forward button disabled when navigation is not possible. For the back button f ...

Exploring the Integration of jQuery AJAX in a Contact Form

I would like to incorporate AJAX functionality into a contact form. Here is the current code I have... $("#contact_form").validate({ meta: "validate", submitHandler: function (form) { $('#contact_form').hide(); ...

strategies for chaining together multiple observables with varying data types and operations

Hey everyone! I'm facing a situation where I have a form with multiple select types, and the options for these inputs are coming from an API. I then take the data emitted from the HTTP request observable and feed it into my FormGroup, and everything i ...

Unraveling in jQuery

Struggling to properly handle the data being returned by JQuery from an API call. Currently encountering an error in the process. Is it possible to iterate through data using a JQuery loop like this? $.each(data.results, function (i, item) { // attemptin ...

Retrieve the values of the rows that have been selected in the Kartik GridView located within a modal, and then transfer

I am attempting to extract data from a Bootstrap modal (which contains a table of Kartik GridView) and pass the selected value to the parent form (an action create form). Can anyone provide guidance on how to achieve this? The modal form includes fields su ...

Dealing with an XML file using JavaScript

Is it possible for JavaScript to interact with an XML file fetched using AJAX? I have a server-side XML file and want to fill fields based on its content. Can I simply read "xmlfile.xml" directly from the server, extract values in JavaScript from the res ...

Is there a way to send a multi-dimensional array using jQuery ajax?

I am encountering an issue with posting an array as a JavaScript variable {{0,0},{1,1},{2,2}} using JSON.Stringify. Whenever I try to post it, I receive an internal server error 500. Can someone please advise on how I can successfully post and utilize this ...

What could be causing the slow compilation of my Next.js pages within the app directory, and what steps can be taken to improve the speed of this

Currently, I am working on a Next.js project that uses the 'app' directory structure. However, during local development, I have been facing significant delays in compile times. Here's a breakdown of the compile times I am encountering: - Th ...

Obtaining the most recently inserted ID in Node.js can be achieved by using

Currently in my Nodejs project, I am using the expressjs framework. I am facing an issue where I am trying to retrieve the "last inserted id", but it is showing as "undefined" in the console. How can I successfully get the last inserted id? Below is the ...

Is localStorage.getItem() method in NextJS components behaving differently?

I'm working on my nextjs application and I wanted to utilize the power of localstorage for storing important data throughout my app. Within the pages directory, specifically in the [slug].tsx file, I implemented the following logic: export default fu ...

Tips on extracting information from an AJAX call using JQuery

My current project involves utilizing a webapi in asp.net that outputs JSON data. I am looking to integrate this webapi with JQuery within a php-created website. The following is the JQuery code I am using to retrieve information from the webapi: $.ajax( ...

Encountering issues when trying to combine Sequelize with TypeScript

As I attempted to transition my NodeJs application to TypeScript, I encountered issues with Sequelize. Upon attempting to implement the code from a website, an error occurred: This expression is not constructable. Type 'typeof import("/home/de ...

Maintain selected dropdown option after page reload

I attempted to preserve the selected item after triggering a reload with an onchange event, however, I encountered this error in the console: "TypeError: o.nodeName is undefined[Learn More]" Here is my select element : <select onchange="showMov(this. ...

Using jQuery to replace the content of a div with a delay?

I am attempting to utilize jQuery to create a fade effect on an element, replace its innerHTML content, and then fade it back in once the new content has been added. I have successfully managed to replace the element's content using the .html() method ...

Is there a way to figure out the number of days from the current date using jQuery UI datepicker?

Hello there, I'm currently facing an issue with calculating the number of days from the present to a chosen date after utilizing a jQuery datepicker. It seems that the date formatting is getting altered upon selection, causing discrepancies in the ca ...

Checkbox fails to trigger onChange when the checked value is controlled by state management

Currently, I am working with a material-ui Table and have been in the process of implementing multi-select functionality on it. The behavior I am aiming for my multi select to exhibit is as follows: Checkboxes should only appear at the beginning of a ro ...

Issue with AngularJS filter not functioning properly

I have a specific situation where I am using an ng-repeat directive in the following manner: {"ng-repeat" => "city in cities() | filter: search"} In this context, each city object is structured like so: { attributes: {name: 'Boston'} } Furt ...

State in Vuex is failing to update effectively when actions are being utilized

I'm trying to wrap my head around VueX, but I'm having trouble getting Axios to work with it. In my store.js file, I have the following setup: state: { cards: [], currentPage: 1, lastPage: 2, }, actions: { loadGradients(page ...