Collapse Multiple Elements HTML

Viewed 61

I'm working on a way to get multiple collapse element working in the same HTML document

My implementation of 1 row expanding a sub-row, work well. But I don't know how to handle it with multiple rows and sub-rows.

Have you any ideas on how I could manage it ?

HTML :

<div class="row-c"> # row n°1
  <div class="row-f">
    <div class="collapse-btn-class">
      <i class="d-arrow collapse-btn rotate"></i>
    </div>
  </div>
  <div class="row-hide collapse-element collapsed"> # sub hidden row n°1
    <div class="table-block"></div>
  </div>
</div>

<div class="row-c"> # row n°2
  <div class="row-f">
    <div class="collapse-btn-class">
      <i class="d-arrow collapse-btn rotate"></i>
    </div>
  </div>
  <div class="row-hide collapse-element collapsed"> # sub hidden row n°2
    <div class="table-block"></div>
  </div>
</div>

CSS :

.collapse-element {
  overflow: hidden;
  transition: max-height 0.3s ease-out;
  display: none;
}

.collapsible {
  max-height: 150px;
  display: grid;
}

JS :

var coll = document.getElementsByClassName("collapse-btn-class");
var i;

for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
  document.querySelector('.collapse-element.collapsed').classList.toggle('collapsible'); # expand or collapse the targeted row
  document.querySelector('.collapse-btn.rotate').classList.toggle('rotated'); # rotate the arrow !not important
        
  });
}
1 Answers

Answering my own question.

I've handled the issue with nextElementSibling and simplifying the structure of classes in the HTML.

I hope it'll help someone else

var coll = document.getElementsByClassName("collapse-btn-class");
    var i;

    for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
        var collapse = this.nextElementSibling;
        if (collapse.style.display === "grid") {
            collapse.style.display = "none";
        }
        else {
            collapse.style.display = "grid";
        }
    });
    }
Related