Yogesh Chauhan's Blog

How to create a Bootstrap style accordion using CSS and JavaScript?

in CSS & JavaScript on March 18, 2021


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.

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Object destructuring in JavaScript: Unpacking fields from objects passed as function parameterJavaScriptbin2hex() and chr() String Functions in PHPPHPJavaScript Number MethodsJavaScriptHow to add a ribbon inside a container using CSS?CSSWhat does it mean by Continuous Integration, Continuous Delivery and Continuous Deployment?MiscellaneousWhat are partials in SCSS (Sass)?SCSS