event listener on click does not change height

What I am trying to build is that: I have two divs which inside have two divs. Initially the inner divs have 0 height. I have added event listeners to the external divs and when I click on a div the height of the internal becomes 50px. In addition I have added event listener to the internal divs and when I click I want the height of the internal dive to become 0 again, but it does not work. Every other css property like width or color did work. Below is the code.

const mainContainer = document.querySelectorAll(".mainContainer");
const subMenu = document.querySelectorAll(".subMenu");

mainContainer.forEach(function(element, index) {
  element.addEventListener("click", function() {
    subMenu[index].style.height = "50px";
  })
})

subMenu.forEach(function(element, index) {
  element.addEventListener("click", function() {
    this.style.height = "10px";
  })
})
* {
  margin: 0;
  padding: 0;
}

#container {
  border: 1px solid red;
  width: 50%;
}

#mainContainer {
  border: 1px solid;
  position: relative;
  width: 100%;
}

.subMenu {
  position: absolute;
  overflow: hidden;
  width: 100%;
  height: 0px;
  background-color: green;
  top: 0;
  left: 0;
  transition: height 0.5s;
}
<div id="container">
  <div class="mainContainer">
    <p>this is the main box</p>
    <p>tha provides the main categories</p>
    <div class="subMenu">
      <p>This is the sub menu</p>
      <p>Lets build it</p>
      <p>Yes we do</p>
    </div>
  </div>
  <div class="mainContainer">
    <p>this is the main box</p>
    <p>tha provides the main categories</p>
    <div class="subMenu">
      <p>This is the sub menu</p>
      <p>Lets build it</p>
      <p>Yes we do</p>
    </div>
  </div>
</div>

24 thoughts on “event listener on click does not change height”

Leave a Comment