Let’s add the HTML first with main container and accordion buttons and contents to open upon click on those buttons.
Let’s add style for the headers and the main accordion container. Bootstrap has borders on headers and the content both so I have added it.
Now, lets style the content sections. For the content we’ll just have borders on sides. The top and bottom borders will be just headers borders.
For the last content box we have to add border bottom since there won’t be more header after that and it can’t get the border from header. We can use :last-child to do so.
I have also used transition, height and opacity properties to create the sliding down animation.
The concept is just show the content box when clicked on header. For that we need to add onclick event on headers. For that, we need to get all header elements. We can use querySelectorAll to do so.
var allAccordions = document.querySelectorAll(".acc");
Once we have that, we can use forEach on the elements array to go through the each one of them and add onclick event.
The advantage of using forEach is we can pass the index and save code in creating the temporary variable for index storage and iteration.
Also, we are gonna use nextElementSibling get the content box for the headers. After that, all we need to do is toggle the properties using simple if-else condition.
Here’s the complete code and demo.
accordion bootstrap forEach onclick opacity querySelectorAll style