Close previously opened accordion with pure JavaScript

I would do it like this. The helper functions act directly on the DOM elements, rather than simulating a click.

//  an array of elements
const allAccordionElements = Array.from(document.querySelectorAll(".accordion__item"));

const run_code = () => {

  //  some helper functions
  const showTab = (el) => {
    el.style.display = "flex";
  };
  const hideTab = (el) => {
    el.style.display = "none";
  };

  if (allAccordionElements.length > 0) {
    
    // open the first one
    showTab(allAccordionElements[0]);
    
    //  hide all others
    allAccordionElements.slice(1).forEach(thisTab => {
      hideTab(thisTab);
    });  
  
  }
  
};

document.getElementById('run').addEventListener('click',run_code);
.accordion__item {
  padding: 0.5em;
  margin: 0.5em;
  border: 2px dotted green;
  background-color: silver;
  display: flex;
}
<div class="accordion">

  <div class="accordion__item">
    item one
  </div>
  <div class="accordion__item">
    item two
  </div>
  <div class="accordion__item">
    item three
  </div>

</div>

<button id="run">run code</button>

Leave a Comment