Call a function with a separate context with a loop

I have this script in which a function is called for every element on page. It works well with separate function calls but if I try to call the function with a unique selector it doesn’t work properly. How can I implement a loop to call the function separately for every html block but using only a class (for example if I have X element) and without addressing them with a separate selector like now (startLoop(‘#stack1’); startLoop(‘#stack2’); ecc. ecc.)

let timer;

function startLoop(container) {
let lastCard = $(container + ' .card').length - 1;
  timer = setInterval(function () {
    let prependList = function() {
      if( $(container + ' .card').hasClass('activeNow') ) { 
        let $slicedCard = $(container + ' .card').slice(lastCard).removeClass('transformThis activeNow');
        $(container + ' ul.card-list').prepend($slicedCard);
      }
    }
    
    $(container + ' li.card').last().addClass('transformThis').prev().addClass('activeNow');
    setTimeout(function(){prependList(); }, 250);
  }, 4500);
}

 if ($('#stack1')[0]) {
  startLoop('#stack1');
}

if ($('#stack2')[0]) {
  startLoop('#stack2');
} 

Answer

Did you try it with .each() ?

Suppose you want to loop through all the elements that have class .stacks

So if you want to loop through all the elements of class .stacks, then you may write it like below:

$(function(){
    $(".stacks").each(function(index, element){
        var elementId = $(element).attr("id");
        startLoop("#" + elementId);
    });
});

// from here your codes start
let timer;

function startLoop(container) {

    let lastCard = $(container).find('.card').length - 1;
      timer = setInterval(function () {
        let prependList = function() {
          if( $(container + ' .card').hasClass('activeNow') ) { 
            let $slicedCard = $(container + ' .card').slice(lastCard).removeClass('transformThis activeNow');
            $(container + ' ul.card-list').prepend($slicedCard);
          }
        }
        
        $(container + ' li.card').last().addClass('transformThis').prev().addClass('activeNow');
        setTimeout(function(){prependList(); }, 250);
      }, 4500);

}