What is the best way to condense all nested elements within a parent element?

I have a collapse element that contains some nested collapse elements.

I am trying to make sure that when the parent collapses, the nested item also collapses. Although it appears to collapse when closed, it does not stay collapsed when I reopen the parent.

I have included the data-bs-parent attribute, but it doesn't seem to be working as expected.

Is there a clear reason why this isn't functioning properly?

You can view the example here - https://codepen.io/s89_/pen/vYamvzg

<div class="row module accordion-toggle collapsed" role="button" data-bs-toggle="collapse"
     data-bs-target="#module-test" aria-expanded="false" aria-controls="module-test">
  <h2>
    <div>
      <div><h3>Collapse</h3></div>
    </div>
  </h2>
  <div id="module-test" class="collapse">
          <div class="row group accordion-toggle collapsed d-flex" data-permissions-collapse-target="group"
           role="button" data-bs-toggle="collapse" data-bs-target="#group-test_events" aria-expanded="false"
           aria-controls="group-test_events" data-bs-parent="#module-test">
        <h2>
          <div>
            <div><h3>Nested collapse item</h3></div>
          </div>
        </h2>
        <div id="group-test_events" class="collapse">
          <div class="">
            Nested collapse contents
          </div>
        </div>
      </div>
  </div>
</div>

Answer №1

To achieve the desired behavior in Bootstrap 5, you can utilize JavaScript instead of jQuery to close the children when necessary. This is because the data-bs-parent attribute does not work for this specific scenario...

const collapsibleModule = document.getElementById('module-test')
collapsibleModule.addEventListener('hidden.bs.collapse', event => {
   // Close children
   event.target.querySelectorAll('.collapse').forEach(element => {
       const bsCollapse = bootstrap.Collapse.getOrCreateInstance(element)
       bsCollapse.hide()
   })
})

https://example.com/code-preview

Answer №2

Enhancing Bootstrap 5 Collapse Feature

To start, I made some slight adjustments to your HTML code for better simplicity.

Collapse Toggle Option:

Here is how a collapse toggle can be implemented:

<div class="collapse-toggle" data-bs-toggle="collapse" data-bs-target="#item">

The use of attributes like data-bs-toggle and data-bs-target defines the functionality of the collapse toggle and its target selection for the corresponding content.

I also introduced a custom class collapse-toggle to easily identify toggle elements.

Working with Collapse Content:

This represents an example of collapsible content:

<div id="content" class="collapse-content collapse">

An id is assigned to establish a relationship between the toggle and this content. While attempting to target the sibling using :scope + *, an alternative approach was found which is elaborated in this stackoverflow post (link).

The presence of the collapse class indicates that this element should remain collapsed by default.

Additionally, a custom class collapse-content is set to specifically recognize content elements.

Automatic Descendant Collapsing Using JS - utilizing 'hidden.bs.collapse' event

To automatically collapse descendants when a parent collapses, I've utilized JavaScript with the hidden.bs.collapse event as outlined in the official documentation here (reference)

// Event listener added for each .collapse-content
$('.collapse-content').on('hidden.bs.collapse', function() {  
  // Find all descendents with .collapse-toggle and loop through them
  $(this).find('.collapse-toggle').each((i, o) => {      
    // Perform hide action on the element following the toggle
    //!A more specific criteria based on the .collapse-content class could be considered here
    $(o).next().collapse('hide');
  })
})
.collapse-toggle {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a0acb1a683f1edfaedf1">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfbdb0b0abacabadbeaf9feaf1eff1ed">[email protected]</a>/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="395b56564d4a4d4b5849790c170b170a">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">


<div>
  <!-- toggle 1 -->
  <div class="collapse-toggle" data-bs-toggle="collapse" data-bs-target="#item">
    <h3>Main Parent</h3>
  </div>
  <!-- content 1 -->
  <div id="item" class="collapse-content collapse">
    <!-- toggle 2 -->
    <div class="collapse-toggle" data-bs-toggle="collapse" data-bs-target="#content">
      <h3>Nested collapse item</h3>
    </div>
    <!-- content 2 -->
    <div id="content" class="collapse-content collapse">
      <p>Nested collapse contents</p>
    </div>
  </div>
</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

Concealing the submit button until a file has been selected

How can I make the submit button invisible until a file is selected? <form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="imageURL[]" id="imageURL" /> <input type="submit" value="submi ...

Verify the presence of blank space with javaScript

I currently have a text box on my website. <input type="text" name="FirstName" value="Mickey"> My goal is to prevent the user from entering empty spaces, tabs, or new lines in the text box. However, I want to allow spaces between characters. Does a ...

Cascading Style Sheets variable and Sassy CSS mixin

I'm facing a challenge involving the use of CSS variables in conjunction with my VueJs app. The goal is to make a hover effect (changing background-color) customizable by the application, while having a default value set in a nested SCSS map using the ...

Styling your printed documents in Next.js 10

Within my Next 10 application, I am able to bring in global styles by importing them in _app.js in the following manner: import 'assets/css/app.css' I want to incorporate a print stylesheet as well. Instead of using a @media print { } query with ...

Can someone guide me on developing a similar design utilizing HTML canvas with HTML 5 technology?

Hey everyone, I could really use some assistance on creating a design with Html 5 canvas. My current issue is that the rectangles I'm trying to generate are overlapping and not fitting properly within the canvas. Below, you'll find both a referen ...

Custom container width causes animation to crash when scrolling

I'm having trouble with my header. When the containers change with scrolling, an animation takes place. Everything works fine with native Bootstrap CSS, but when I customize the width of the container in my custom CSS (the width set to 1140px), the an ...

The insider's guide to understanding the inner workings of the :nth-child() property

I am finding the :nth-child() property to be a bit confusing. Sometimes it takes arguments like :nth-child(2),:nth-child(2n),:nth-child(2n + 1). I'm not sure what these mean exactly - are they referring to even or odd divs, or is there another propert ...

Guide to positioning elements in CSS

I'm struggling to get all the elements to align in a single row. I've tried using display: inline-block, but it's not working as expected. I'm working with DataTables and I want the button images to be aligned with the page number box. ...

Blending PHP with jQuery

I'm currently working on the same page as before but this time, I'm using it to experiment with jQuery. I'm trying to learn it for my 'boss', but unfortunately, I can't seem to get the JavaScript in this file to run at all, le ...

The results of running 'npm run dev' and 'npm run build prod' are different from each other

Currently, I am in the process of developing a progressive web app using Vue.js. During development, I utilize the command npm run dev to initiate the local server that serves the files over at http://localhost:8080/. When it comes time to build for produ ...

Ways to utilize jquery script within a react component

<script> $(document).ready(function() { var source; var destination; var fn = function(event, ui) { toDrop = $(ui.draggable).clone(); if ($("#droppable").find("li[uniqueIdentity=" ...

Is there a way to automatically redirect the main html page to a different html page upon logging in?

I have created a main page in HTML with a login box that displays a message saying "Login successful" or "Login failed" based on whether the password entered is 8 characters or more. The validation function for this works correctly, but after successfully ...

Challenges in Maintaining the Integrity of HTML5 Semantic Tags (article, footer, header)

When it comes to the new layout tags in HTML5, how effectively do they degrade? What risks are involved in using them? (I'm excluding <video>-- as I've come across specific fallback code for it). For instance, consider the following snippe ...

iPhone-compatible iFrame with adaptable webpage dimensions

While attempting to embed our page on a client's site, everything looks great in a browser and our media queries are functioning properly. However, we encountered an issue when viewing the embedded page inside an iframe on an iDevice. It seems that th ...

Simplified user interface for detecting radio button clicks

Currently working on a form that includes radio buttons, where an update function is triggered whenever there is a user input change. The challenge I am facing is how to incorporate user-friendly radio buttons with a larger button area encompassing both t ...

Obtaining Text within <span>Tag</span> with Selenium in C#

I am encountering an issue when trying to retrieve the Subject title of an email from Unread emails using Selenium Webdriver with C#. Below is the HTML code provided : <div class="ae4 UI UJ" gh="tl"> <div class="Cp"> <div> <ta ...

Question about transparency - HTML, CSS, and Bootstrap

I adjusted the opacity of the bootstrap card to 0.8, but now I want the table to be opaque while the rest of the card remains translucent. How can I achieve this effect? I attempted to add the style opacity : 1 to the table, but it didn't have the des ...

Looking to have the image float after reducing the size of the windows in html?

For my webpage, I want an image to appear on the extreme left when the browser is maximized, but then move to the extreme right when the browser is minimized. I've tried using float, but it doesn't seem to be working. Any suggestions on how to ac ...

"Concealing children elements disrupts the functionality of the CSS grid layout

Is there a way to prevent layout issues when using CSS to dynamically display items? For example, when hiding button A it causes the Edit button to shift to the left instead of sticking to the right edge of the grid as expected. <html> <body> ...

Obtain the text content of a div using JavaScript

Hello, I am new to Javascript! I have a table structure that looks like this: <table id='master_tbl'> <tbody> <tr id="master_hr'> <td class="myclass"> <table> <tbody ...