I want to use the carousel from Bootstrap 4 for showing dynamic content. The first item of the carousel needs the css class ".active". Actually this should be added directly in the HTML but this is a bit stricky with the my output of dynamic content. Therefore I want to add it through JavaScript and I found this topic: Appending a class to the first div of a set of dynamically created divs
The solution is to add the following JavaScript before the closing body-tag:
$(".carousel-item:first").addClass('active');
That works so far but only if you have one carousel on your page. If you have more than, this only works for the first carousel in the code.
What I did now is to add a custom class (carousel1, carousel2, carousel3,...) to each carousel on the page and add one line for each carousel to my JavaScript file like:
$(".carousel-item.carousel1:first").addClass('active');
$(".carousel-item.carousel2:first").addClass('active');
$(".carousel-item.carousel3:first").addClass('active');
BUT: To be more flexible, is there a JavaScript solution as well that it works more generic and without a custom css class per carousel?
Thanks for any hints and tips in advance.
Bastian