I am utilizing Bootstrap 4's carousel to showcase dynamic content. The challenge lies in marking the first item of the carousel with the CSS class ".active". While it is typically added directly in the HTML, it becomes complicated when dealing with dynamic content output. Upon researching, I stumbled upon this discussion: Appending a class to the first div of a set of dynamically created divs
The workaround involves injecting the following JavaScript before the closing body-tag:
$(".carousel-item:first").addClass('active');
This method works effectively for a single carousel on the page. However, if multiple carousels exist, the approach only targets the first instance in the code.
To address this limitation, I've adopted a strategy where each carousel is assigned a unique custom class (carousel1, carousel2, carousel3,...) and incorporated corresponding lines into my JavaScript file like so:
$(".carousel-item.carousel1:first").addClass('active');
$(".carousel-item.carousel2:first").addClass('active');
$(".carousel-item.carousel3:first").addClass('active');
YET: Is there a more versatile JavaScript solution that functions in a generic manner without necessitating individual css classes per carousel?
I appreciate any insights and recommendations provided beforehand.
Bastian