Aakash Goel Aakash Goel - 4 months ago 23
jQuery Question

Twitter bootstrap Make first panel of accordion open by default

I am using twitter bootstrap to make accordions on the page. I want to make the first panel open on each page. This is the code that I wrote:

var accordion_list = $(".prime-content .accordion-body");
accordion_list.each(function(index, element){
accordion_list.addClass(index == 0 ? "in" : "");
});


This however, is adding "in" class to all the elements. What needs to be fixed?

Answer

You are adding the class to the whole accordion_list collection of elements but you need to add it to the currently iterated element instead.

$(".prime-content .accordion-body").each(function(index, element){
  $(element).addClass(index == 0 ? "in" : "");
});

If you don't do anything else in the loop you can also make it shorter:

accordion_list.first().addClass("in");