Skip to content

How to add class on the first & last element that has specific class inside multiple same elements class?

Im trying to add class on class on first & last child element with ONLY .active class. I found the code here:

jQuery(document).ready(function($) {

    var carousel = $(".latest-work-carousel");
        loop : true,
        items : 3,
        nav : true,
        dots : false,

    carousel.on('translated.owl.carousel', function(event) {

    function checkClasses(){
        var total = $('.latest-work-carousel .owl-stage').length;

        $('.latest-work-carousel .owl-stage .owl-item').removeClass('firstActiveItem lastActiveItem');

        $('.latest-work-carousel .owl-stage').each(function(index){
            if (index === 0) {
                // this is the first one
            if (index === total - 1 && total>1) {
                // this is the last one


It does work, however my problem is that the firstActiveItem class is only applied inside the first carousel and the lastActiveItem class inside second carousel.

How do i make it applies on all carousel regardless of how many carousel i have with same class?

Here’s my complete code fiddle:


You can iterate over .owl-carousel elements and find the target element from the current .owl-carousel‘s children on every iteration. With this approach no matter how many carousels exists on the page. like this: